diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/main/java/pl/agh/enrollme/model/Person.java b/src/main/java/pl/agh/enrollme/model/Person.java index b78dbc0..c40ec33 100644 --- a/src/main/java/pl/agh/enrollme/model/Person.java +++ b/src/main/java/pl/agh/enrollme/model/Person.java @@ -1,263 +1,263 @@ package pl.agh.enrollme.model; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import javax.persistence.*; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.List; @Entity public class Person implements Serializable, UserDetails { @Transient private static final long serialVersionUID = -5777367229609230476L; @Transient private final List<GrantedAuthority> authorityList = new ArrayList<>(); @Id @GeneratedValue private Integer id = 0; private String password = ""; @Column(unique = true) private String username = ""; private String firstName = ""; private String lastName = ""; @Column(unique = true) private Integer indeks; private Boolean accountNonExpired = true; private Boolean accountNonLocked = true; private Boolean credentialsNonExpired = true; private Boolean enabled = true; private String rolesToken = "ROLE_USER"; @ManyToMany(fetch = FetchType.LAZY, mappedBy = "persons", cascade = CascadeType.ALL) private List<Group> groups; @ManyToMany(mappedBy = "persons", fetch = FetchType.LAZY, cascade = CascadeType.ALL) private List<Subject> subjects; @ManyToMany(mappedBy = "persons", fetch = FetchType.LAZY) private List<Enroll> availableEnrolls; public Person() { } public Person(String password, String username, String firstName, String lastName, Integer indeks, Boolean accountNonExpired, Boolean accountNonLocked, Boolean credentialsNonExpired, Boolean enabled, String rolesToken, List<Group> groups, List<Subject> subjects) { this.password = password; this.username = username; this.firstName = firstName; this.lastName = lastName; this.indeks = indeks; this.accountNonExpired = accountNonExpired; this.accountNonLocked = accountNonLocked; this.credentialsNonExpired = credentialsNonExpired; this.enabled = enabled; this.rolesToken = rolesToken; this.groups = groups; this.subjects = subjects; } public void addSubject(Subject subject) { subjects.add(subject); } public void addGroups(Group group) { groups.add(group); } public Integer getIndeks() { return indeks; } public void setIndeks(Integer indeks) { this.indeks = indeks; } public String getFirstName() { return firstName; } public List<Enroll> getAvailableEnrolls() { return availableEnrolls; } public void setAvailableEnrolls(List<Enroll> availableEnrolls) { this.availableEnrolls = availableEnrolls; } public void setGroups(List<Group> groups) { this.groups = groups; } public void setSubjects(List<Subject> subjects) { this.subjects = subjects; } public List<Group> getGroups() { return groups; } public List<Subject> getSubjects() { return subjects; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { updateAuthorityList(rolesToken); return authorityList; } @Override public String getPassword() { return password; } @Override public String getUsername() { return username; } @Override public boolean isAccountNonExpired() { return accountNonExpired; } @Override public boolean isAccountNonLocked() { return accountNonLocked; } @Override public boolean isCredentialsNonExpired() { return credentialsNonExpired; } @Override public boolean isEnabled() { return enabled; } public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } public void setAccountNonExpired(Boolean accountNonExpired) { this.accountNonExpired = accountNonExpired; } public void setAccountNonLocked(Boolean accountNonLocked) { this.accountNonLocked = accountNonLocked; } public void setCredentialsNonExpired(Boolean credentialsNonExpired) { this.credentialsNonExpired = credentialsNonExpired; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public String getRolesToken() { return rolesToken; } public void setRolesToken(String roles) { this.rolesToken = roles; updateAuthorityList(roles); } /** * Updates authority list based on rolestoken provided. Uses regex to split roles into tokens. * Accepts role tokens such as: ROLE_1, ROLE_2 :;| ROLE_3:::ROLE_4 * @param roles */ private void updateAuthorityList(String roles) { final String[] split = roles.split("[.,;: |]+"); authorityList.clear(); for (String token : split) { authorityList.add(new SimpleGrantedAuthority(token.trim().toUpperCase())); } } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Person)) return false; Person person = (Person) o; if (!username.equals(person.username)) return false; return true; } @Override public int hashCode() { return username.hashCode(); } @Override public String toString() { return "Person{" + "authorityList=" + authorityList + ", id=" + id + ", password='" + password + '\'' + ", username='" + username + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", indeks=" + indeks + ", accountNonExpired=" + accountNonExpired + ", accountNonLocked=" + accountNonLocked + ", credentialsNonExpired=" + credentialsNonExpired + ", enabled=" + enabled + ", rolesToken='" + rolesToken + '\'' + - ", groups=" + groups + - ", subjects=" + subjects + - ", availableEnrolls=" + availableEnrolls + + //", groups=" + groups + + //", subjects=" + subjects + + //", availableEnrolls=" + availableEnrolls + '}'; } }
true
true
public String toString() { return "Person{" + "authorityList=" + authorityList + ", id=" + id + ", password='" + password + '\'' + ", username='" + username + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", indeks=" + indeks + ", accountNonExpired=" + accountNonExpired + ", accountNonLocked=" + accountNonLocked + ", credentialsNonExpired=" + credentialsNonExpired + ", enabled=" + enabled + ", rolesToken='" + rolesToken + '\'' + ", groups=" + groups + ", subjects=" + subjects + ", availableEnrolls=" + availableEnrolls + '}'; }
public String toString() { return "Person{" + "authorityList=" + authorityList + ", id=" + id + ", password='" + password + '\'' + ", username='" + username + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", indeks=" + indeks + ", accountNonExpired=" + accountNonExpired + ", accountNonLocked=" + accountNonLocked + ", credentialsNonExpired=" + credentialsNonExpired + ", enabled=" + enabled + ", rolesToken='" + rolesToken + '\'' + //", groups=" + groups + //", subjects=" + subjects + //", availableEnrolls=" + availableEnrolls + '}'; }
diff --git a/milton-api/src/main/java/com/bradmcevoy/http/http11/DefaultHttp11ResponseHandler.java b/milton-api/src/main/java/com/bradmcevoy/http/http11/DefaultHttp11ResponseHandler.java index 83d8828..b7cc124 100644 --- a/milton-api/src/main/java/com/bradmcevoy/http/http11/DefaultHttp11ResponseHandler.java +++ b/milton-api/src/main/java/com/bradmcevoy/http/http11/DefaultHttp11ResponseHandler.java @@ -1,413 +1,419 @@ package com.bradmcevoy.http.http11; import com.bradmcevoy.http.*; import com.bradmcevoy.http.Response.Status; import com.bradmcevoy.http.exceptions.BadRequestException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Date; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.bradmcevoy.http.exceptions.NotAuthorizedException; import com.bradmcevoy.io.BufferingOutputStream; import com.bradmcevoy.io.ReadingException; import com.bradmcevoy.io.StreamUtils; import com.bradmcevoy.io.WritingException; import java.io.InputStream; import org.apache.commons.io.IOUtils; /** * */ public class DefaultHttp11ResponseHandler implements Http11ResponseHandler { public enum BUFFERING { always, never, whenNeeded } private static final Logger log = LoggerFactory.getLogger( DefaultHttp11ResponseHandler.class ); public static final String METHOD_NOT_ALLOWED_HTML = "<html><body><h1>Method Not Allowed</h1></body></html>"; public static final String NOT_FOUND_HTML = "<html><body><h1>${url} Not Found (404)</h1></body></html>"; public static final String METHOD_NOT_IMPLEMENTED_HTML = "<html><body><h1>Method Not Implemented</h1></body></html>"; public static final String CONFLICT_HTML = "<html><body><h1>Conflict</h1></body></html>"; public static final String SERVER_ERROR_HTML = "<html><body><h1>Server Error</h1></body></html>"; public static final String NOT_AUTHORISED_HTML = "<html><body><h1>Not authorised</h1></body></html>"; private final AuthenticationService authenticationService; private final ETagGenerator eTagGenerator; private CacheControlHelper cacheControlHelper = new DefaultCacheControlHelper(); private int maxMemorySize = 100000; private BUFFERING buffering; public DefaultHttp11ResponseHandler(AuthenticationService authenticationService) { this.authenticationService = authenticationService; this.eTagGenerator = new DefaultETagGenerator(); } public DefaultHttp11ResponseHandler(AuthenticationService authenticationService, ETagGenerator eTagGenerator) { this.authenticationService = authenticationService; this.eTagGenerator = eTagGenerator; } /** * Defaults to com.bradmcevoy.http.http11.DefaultCacheControlHelper * @return */ public CacheControlHelper getCacheControlHelper() { return cacheControlHelper; } public void setCacheControlHelper(CacheControlHelper cacheControlHelper) { this.cacheControlHelper = cacheControlHelper; } public String generateEtag(Resource r) { return eTagGenerator.generateEtag(r); } public void respondWithOptions(Resource resource, Response response, Request request, List<String> methodsAllowed) { response.setStatus(Response.Status.SC_OK); response.setAllowHeader(methodsAllowed); response.setContentLengthHeader((long) 0); } public void respondNotFound(Response response, Request request) { response.setStatus(Response.Status.SC_NOT_FOUND); response.setContentTypeHeader("text/html"); PrintWriter pw = new PrintWriter(response.getOutputStream(), true); String s = NOT_FOUND_HTML.replace("${url}", request.getAbsolutePath()); pw.print(s); pw.flush(); } public void respondUnauthorised(Resource resource, Response response, Request request) { log.trace("respondUnauthorised"); response.setStatus(Response.Status.SC_UNAUTHORIZED); List<String> challenges = authenticationService.getChallenges(resource, request); response.setAuthenticateHeader(challenges); // PrintWriter pw = new PrintWriter(response.getOutputStream(), true); // // // http://jira.ettrema.com:8080/browse/MIL-39 // String s = NOT_AUTHORISED_HTML.replace("${url}", request.getAbsolutePath()); // response.setContentLengthHeader((long)s.length()); // pw.print(s); // pw.flush(); } public void respondMethodNotImplemented(Resource resource, Response response, Request request) { // log.debug( "method not implemented. resource: " + resource.getClass().getName() + " - method " + request.getMethod() ); try { response.setStatus(Response.Status.SC_NOT_IMPLEMENTED); OutputStream out = response.getOutputStream(); out.write(METHOD_NOT_IMPLEMENTED_HTML.getBytes()); } catch (IOException ex) { log.warn("exception writing content"); } } public void respondMethodNotAllowed(Resource res, Response response, Request request) { log.debug("method not allowed. handler: " + this.getClass().getName() + " resource: " + res.getClass().getName()); try { response.setStatus(Response.Status.SC_METHOD_NOT_ALLOWED); OutputStream out = response.getOutputStream(); out.write(METHOD_NOT_ALLOWED_HTML.getBytes()); } catch (IOException ex) { log.warn("exception writing content"); } } /** * * @param resource * @param response * @param message - optional message to output in the body content */ public void respondConflict(Resource resource, Response response, Request request, String message) { log.debug("respondConflict"); try { response.setStatus(Response.Status.SC_CONFLICT); OutputStream out = response.getOutputStream(); out.write(CONFLICT_HTML.getBytes()); } catch (IOException ex) { log.warn("exception writing content"); } } public void respondRedirect(Response response, Request request, String redirectUrl) { if (redirectUrl == null) { throw new NullPointerException("redirectUrl cannot be null"); } log.trace("respondRedirect"); // delegate to the response, because this can be server dependent response.sendRedirect(redirectUrl); // response.setStatus(Response.Status.SC_MOVED_TEMPORARILY); // response.setLocationHeader(redirectUrl); } public void respondExpectationFailed(Response response, Request request) { response.setStatus(Response.Status.SC_EXPECTATION_FAILED); } public void respondCreated(Resource resource, Response response, Request request) { // log.debug( "respondCreated" ); response.setStatus(Response.Status.SC_CREATED); } public void respondNoContent(Resource resource, Response response, Request request) { // log.debug( "respondNoContent" ); //response.setStatus(Response.Status.SC_OK); // see comments in http://www.ettrema.com:8080/browse/MIL-87 response.setStatus(Response.Status.SC_NO_CONTENT); } public void respondPartialContent(GetableResource resource, Response response, Request request, Map<String, String> params, Range range) throws NotAuthorizedException, BadRequestException { log.debug("respondPartialContent: " + range.getStart() + " - " + range.getFinish()); response.setStatus(Response.Status.SC_PARTIAL_CONTENT); response.setContentRangeHeader(range.getStart(), range.getFinish(), resource.getContentLength()); response.setDateHeader(new Date()); String etag = eTagGenerator.generateEtag(resource); if (etag != null) { response.setEtag(etag); } String acc = request.getAcceptHeader(); String ct = resource.getContentType(acc); if (ct != null) { response.setContentTypeHeader(ct); } try { resource.sendContent(response.getOutputStream(), range, params, ct); } catch (IOException ex) { log.warn("IOException writing to output, probably client terminated connection", ex); } } public void respondHead(Resource resource, Response response, Request request) { setRespondContentCommonHeaders(response, resource, Response.Status.SC_NO_CONTENT, request.getAuthorization()); } public void respondContent(Resource resource, Response response, Request request, Map<String, String> params) throws NotAuthorizedException, BadRequestException { log.debug("respondContent: " + resource.getClass()); Auth auth = request.getAuthorization(); setRespondContentCommonHeaders(response, resource, auth); if (resource instanceof GetableResource) { GetableResource gr = (GetableResource) resource; String acc = request.getAcceptHeader(); String ct = gr.getContentType(acc); if (ct != null) { ct = pickBestContentType(ct); response.setContentTypeHeader(ct); } cacheControlHelper.setCacheControl(gr, response, request.getAuthorization()); Long contentLength = gr.getContentLength(); - if (buffering == BUFFERING.always || (contentLength != null && buffering == BUFFERING.whenNeeded)) { // often won't know until rendered + boolean doBuffering; + if( buffering == null || buffering == BUFFERING.whenNeeded ) { + doBuffering = (contentLength == null); // if no content length then we buffer content to find content length + } else { + doBuffering = (buffering == BUFFERING.always); // if not null or whenNeeded then buffering is explicitly enabled or disabled + } + if (!doBuffering) { log.trace("sending content with known content length: " + contentLength); response.setContentLengthHeader(contentLength); sendContent(request, response, (GetableResource) resource, params, null, ct); } else { log.trace("buffering content..."); BufferingOutputStream tempOut = new BufferingOutputStream(maxMemorySize); try { ((GetableResource) resource).sendContent(tempOut, null, params, ct); tempOut.close(); } catch (IOException ex) { tempOut.deleteTempFileIfExists(); throw new RuntimeException("Exception generating buffered content", ex); } Long bufContentLength = tempOut.getSize(); if (contentLength != null) { if (!contentLength.equals(bufContentLength)) { throw new RuntimeException("Lengthd dont match: " + contentLength + " != " + bufContentLength); } } log.trace("sending buffered content..."); response.setContentLengthHeader(bufContentLength); InputStream in = tempOut.getInputStream(); try { StreamUtils.readTo(in, response.getOutputStream()); } catch (ReadingException ex) { throw new RuntimeException(ex); } catch (WritingException ex) { log.warn("exception writing, client probably closed connection", ex); } finally { IOUtils.closeQuietly(in); // make sure we close to delete temporary file } return; } } } public void respondNotModified(GetableResource resource, Response response, Request request) { log.trace("respondNotModified"); response.setStatus(Response.Status.SC_NOT_MODIFIED); response.setDateHeader(new Date()); String etag = eTagGenerator.generateEtag(resource); if (etag != null) { response.setEtag(etag); } // Note that we use a simpler modified date handling here then when // responding with content, because in a not-modified situation the // modified date MUST be that of the actual resource Date modDate = resource.getModifiedDate(); response.setLastModifiedHeader(modDate); cacheControlHelper.setCacheControl(resource, response, request.getAuthorization()); } protected void sendContent(Request request, Response response, GetableResource resource, Map<String, String> params, Range range, String contentType) throws NotAuthorizedException, BadRequestException { long l = System.currentTimeMillis(); log.trace("sendContent"); OutputStream out = outputStreamForResponse(request, response, resource); try { resource.sendContent(out, null, params, contentType); out.flush(); if (log.isTraceEnabled()) { l = System.currentTimeMillis() - l; log.trace("sendContent finished in " + l + "ms"); } } catch (IOException ex) { log.warn("IOException sending content", ex); } } protected OutputStream outputStreamForResponse(Request request, Response response, GetableResource resource) { OutputStream outToUse = response.getOutputStream(); return outToUse; } protected void output(final Response response, final String s) { PrintWriter pw = new PrintWriter(response.getOutputStream(), true); pw.print(s); pw.flush(); } protected void setRespondContentCommonHeaders(Response response, Resource resource, Auth auth) { setRespondContentCommonHeaders(response, resource, Response.Status.SC_OK, auth); } protected void setRespondContentCommonHeaders(Response response, Resource resource, Response.Status status, Auth auth) { response.setStatus(status); response.setDateHeader(new Date()); String etag = eTagGenerator.generateEtag(resource); if (etag != null) { response.setEtag(etag); } setModifiedDate(response, resource, auth); } /** The modified date response header is used by the client for content caching. It seems obvious that if we have a modified date on the resource we should set it. BUT, because of the interaction with max-age we should always set it to the current date if we have max-age The problem, is that if we find that a condition GET has an expired mod-date (based on maxAge) then we want to respond with content (even if our mod-date hasnt changed. But if we use the actual mod-date in that case, then the browser will continue to use the old mod-date, so will forever more respond with content. So we send a mod-date of now to ensure that future requests will be given a 304 not modified.* * * @param response * @param resource * @param auth */ public static void setModifiedDate(Response response, Resource resource, Auth auth) { Date modDate = resource.getModifiedDate(); if (modDate != null) { // HACH - see if this helps IE response.setLastModifiedHeader(modDate); // if (resource instanceof GetableResource) { // GetableResource gr = (GetableResource) resource; // Long maxAge = gr.getMaxAgeSeconds(auth); // if (maxAge != null && maxAge > 0) { // log.trace("setModifiedDate: has a modified date and a positive maxAge, so adjust modDate"); // long tm = System.currentTimeMillis() - 60000; // modified 1 minute ago // modDate = new Date(tm); // have max-age, so use current date // } // } // response.setLastModifiedHeader(modDate); } } public void respondBadRequest(Resource resource, Response response, Request request) { response.setStatus(Response.Status.SC_BAD_REQUEST); } public void respondForbidden(Resource resource, Response response, Request request) { response.setStatus(Response.Status.SC_FORBIDDEN); } public void respondDeleteFailed(Request request, Response response, Resource resource, Status status) { response.setStatus(status); } public AuthenticationService getAuthenticationService() { return authenticationService; } public void respondServerError(Request request, Response response, String reason) { try { response.setStatus(Status.SC_INTERNAL_SERVER_ERROR); OutputStream out = response.getOutputStream(); out.write(SERVER_ERROR_HTML.getBytes()); } catch (IOException ex) { throw new RuntimeException(ex); } } /** * Maximum size of data to hold in memory per request when buffering output * data. * * @return */ public int getMaxMemorySize() { return maxMemorySize; } public void setMaxMemorySize(int maxMemorySize) { this.maxMemorySize = maxMemorySize; } public BUFFERING getBuffering() { return buffering; } public void setBuffering(BUFFERING buffering) { this.buffering = buffering; } /** * Sometimes we'll get a content type list, such as image/jpeg,image/pjpeg * * In this case we should pick the first in the list * * @param ct * @return */ private String pickBestContentType(String ct) { if( ct == null ) { return null; } else if( ct.contains(",")) { return ct.split(",")[0]; } else { return ct; } } }
true
true
public void respondContent(Resource resource, Response response, Request request, Map<String, String> params) throws NotAuthorizedException, BadRequestException { log.debug("respondContent: " + resource.getClass()); Auth auth = request.getAuthorization(); setRespondContentCommonHeaders(response, resource, auth); if (resource instanceof GetableResource) { GetableResource gr = (GetableResource) resource; String acc = request.getAcceptHeader(); String ct = gr.getContentType(acc); if (ct != null) { ct = pickBestContentType(ct); response.setContentTypeHeader(ct); } cacheControlHelper.setCacheControl(gr, response, request.getAuthorization()); Long contentLength = gr.getContentLength(); if (buffering == BUFFERING.always || (contentLength != null && buffering == BUFFERING.whenNeeded)) { // often won't know until rendered log.trace("sending content with known content length: " + contentLength); response.setContentLengthHeader(contentLength); sendContent(request, response, (GetableResource) resource, params, null, ct); } else { log.trace("buffering content..."); BufferingOutputStream tempOut = new BufferingOutputStream(maxMemorySize); try { ((GetableResource) resource).sendContent(tempOut, null, params, ct); tempOut.close(); } catch (IOException ex) { tempOut.deleteTempFileIfExists(); throw new RuntimeException("Exception generating buffered content", ex); } Long bufContentLength = tempOut.getSize(); if (contentLength != null) { if (!contentLength.equals(bufContentLength)) { throw new RuntimeException("Lengthd dont match: " + contentLength + " != " + bufContentLength); } } log.trace("sending buffered content..."); response.setContentLengthHeader(bufContentLength); InputStream in = tempOut.getInputStream(); try { StreamUtils.readTo(in, response.getOutputStream()); } catch (ReadingException ex) { throw new RuntimeException(ex); } catch (WritingException ex) { log.warn("exception writing, client probably closed connection", ex); } finally { IOUtils.closeQuietly(in); // make sure we close to delete temporary file } return; } } }
public void respondContent(Resource resource, Response response, Request request, Map<String, String> params) throws NotAuthorizedException, BadRequestException { log.debug("respondContent: " + resource.getClass()); Auth auth = request.getAuthorization(); setRespondContentCommonHeaders(response, resource, auth); if (resource instanceof GetableResource) { GetableResource gr = (GetableResource) resource; String acc = request.getAcceptHeader(); String ct = gr.getContentType(acc); if (ct != null) { ct = pickBestContentType(ct); response.setContentTypeHeader(ct); } cacheControlHelper.setCacheControl(gr, response, request.getAuthorization()); Long contentLength = gr.getContentLength(); boolean doBuffering; if( buffering == null || buffering == BUFFERING.whenNeeded ) { doBuffering = (contentLength == null); // if no content length then we buffer content to find content length } else { doBuffering = (buffering == BUFFERING.always); // if not null or whenNeeded then buffering is explicitly enabled or disabled } if (!doBuffering) { log.trace("sending content with known content length: " + contentLength); response.setContentLengthHeader(contentLength); sendContent(request, response, (GetableResource) resource, params, null, ct); } else { log.trace("buffering content..."); BufferingOutputStream tempOut = new BufferingOutputStream(maxMemorySize); try { ((GetableResource) resource).sendContent(tempOut, null, params, ct); tempOut.close(); } catch (IOException ex) { tempOut.deleteTempFileIfExists(); throw new RuntimeException("Exception generating buffered content", ex); } Long bufContentLength = tempOut.getSize(); if (contentLength != null) { if (!contentLength.equals(bufContentLength)) { throw new RuntimeException("Lengthd dont match: " + contentLength + " != " + bufContentLength); } } log.trace("sending buffered content..."); response.setContentLengthHeader(bufContentLength); InputStream in = tempOut.getInputStream(); try { StreamUtils.readTo(in, response.getOutputStream()); } catch (ReadingException ex) { throw new RuntimeException(ex); } catch (WritingException ex) { log.warn("exception writing, client probably closed connection", ex); } finally { IOUtils.closeQuietly(in); // make sure we close to delete temporary file } return; } } }
diff --git a/src/org/ohmage/service/MobilityServices.java b/src/org/ohmage/service/MobilityServices.java index d9b28813..a0e2e237 100644 --- a/src/org/ohmage/service/MobilityServices.java +++ b/src/org/ohmage/service/MobilityServices.java @@ -1,363 +1,364 @@ /******************************************************************************* * Copyright 2012 The Regents of the University of California * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.ohmage.service; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.joda.time.DateTime; import org.ohmage.domain.MobilityPoint; import org.ohmage.domain.MobilityPoint.LocationStatus; import org.ohmage.domain.MobilityPoint.Mode; import org.ohmage.domain.MobilityPoint.SensorData; import org.ohmage.exception.DataAccessException; import org.ohmage.exception.DomainException; import org.ohmage.exception.ServiceException; import org.ohmage.query.IUserMobilityQueries; import edu.ucla.cens.mobilityclassifier.Classification; import edu.ucla.cens.mobilityclassifier.MobilityClassifier; import edu.ucla.cens.mobilityclassifier.Sample; import edu.ucla.cens.mobilityclassifier.WifiScan; /** * This class is responsible for all services pertaining to Mobility points. * * @author John Jenkins */ public final class MobilityServices { /** * This is the maximum number of milliseconds before a Mobility point that * we need to get the WiFi data for the classifier. */ private static final long MAX_MILLIS_OF_PREVIOUS_WIFI_DATA = 1000 * 60 * 10; private static MobilityServices instance; private IUserMobilityQueries userMobilityQueries; /** * Default constructor. Privately instantiated via dependency injection * (reflection). * * @throws IllegalStateException if an instance of this class already * exists * * @throws IllegalArgumentException if iUserMobilityQueries is null */ private MobilityServices(IUserMobilityQueries iUserMobilityQueries) { if(instance != null) { throw new IllegalStateException("An instance of this class already exists."); } if(iUserMobilityQueries == null) { throw new IllegalArgumentException("An instance of IUserMobilityQueries is required."); } userMobilityQueries = iUserMobilityQueries; instance = this; } /** * @return Returns the singleton instance of this class. */ public static MobilityServices instance() { return instance; } /** * Adds the Mobility point to the database. * * @param mobilityPoints A list of Mobility points to be added to the * database. * * @throws ServiceException Thrown if there is an error. */ public void createMobilityPoint(final String username, final String client, final List<MobilityPoint> mobilityPoints) throws ServiceException { if(username == null) { throw new ServiceException("The username cannot be null."); } else if(client == null) { throw new ServiceException("The client cannot be null."); } try { for(MobilityPoint mobilityPoint : mobilityPoints) { userMobilityQueries.createMobilityPoint(username, client, mobilityPoint); } } catch(DataAccessException e) { throw new ServiceException(e); } } /** * Runs the classifier against all of the Mobility points in the list. * * @param mobilityPoints The Mobility points that are to be classified by * the server. * * @throws ServiceException Thrown if there is an error with the * classification service. */ public void classifyData( final String uploadersUsername, final List<MobilityPoint> mobilityPoints) throws ServiceException { // If the list is empty, just exit. if(mobilityPoints == null) { return; } // Create a new classifier. MobilityClassifier classifier = new MobilityClassifier(); // Create place holders for the previous data. String previousWifiMode = null; List<WifiScan> previousWifiScans = new LinkedList<WifiScan>(); if(mobilityPoints.size() > 0) { try { + MobilityPoint firstPoint = mobilityPoints.get(0); DateTime startDate = new DateTime(); startDate = new DateTime( - mobilityPoints.get(0).getTime() - + firstPoint.getTime() - MAX_MILLIS_OF_PREVIOUS_WIFI_DATA); List<MobilityPoint> previousPoints = userMobilityQueries.getMobilityInformation( uploadersUsername, startDate, - null, + new DateTime(firstPoint.getTime()), null, null, null); for(MobilityPoint previousPoint : previousPoints) { try { previousWifiScans.add(previousPoint.getWifiScan()); } catch(DomainException e) { // This point does not have a WifiScan, so we will skip // it. } } } catch(DataAccessException e) { throw new ServiceException(e); } } // For each of the Mobility points, for(MobilityPoint mobilityPoint : mobilityPoints) { // If the data point is of type error, don't attempt to classify // it. if(mobilityPoint.getMode().equals(Mode.ERROR)) { continue; } // If the SubType is sensor data, if(MobilityPoint.SubType.SENSOR_DATA.equals(mobilityPoint.getSubType())) { SensorData currSensorData = mobilityPoint.getSensorData(); // Get the Samples from this new point. List<Sample> samples; try { samples = mobilityPoint.getSamples(); } catch(DomainException e) { throw new ServiceException( "There was a problem retrieving the samples.", e); } // Get the new WifiScan from this new point. WifiScan wifiScan; if(mobilityPoint.getSensorData().getWifiData() == null) { wifiScan = null; } else { try { wifiScan = mobilityPoint.getWifiScan(); } catch(DomainException e) { throw new ServiceException( "The Mobility point does not contain WiFi data.", e); } } // Prune out the old WifiScans that are more than 10 minutes // old. long minPreviousTime = mobilityPoint.getTime() - MAX_MILLIS_OF_PREVIOUS_WIFI_DATA; Iterator<WifiScan> previousWifiScansIter = previousWifiScans.iterator(); while(previousWifiScansIter.hasNext()) { if(previousWifiScansIter.next().getTime() < minPreviousTime) { previousWifiScansIter.remove(); } else { // Given the fact that the list is ordered, we can now // be assured that all of the remaining WiFi scans are // invalid. break; } } // Classify the data. Classification classification = classifier.classify( samples, currSensorData.getSpeed(), wifiScan, previousWifiScans, previousWifiMode); // Update the place holders for the previous data. if(wifiScan != null) { previousWifiScans.add(wifiScan); } previousWifiMode = classification.getWifiMode(); // If the classification generated some results, pull them out // and store them in the Mobility point. if(classification.hasFeatures()) { try { mobilityPoint.setClassifierData( classification.getFft(), classification.getVariance(), classification.getAverage(), MobilityPoint.Mode.valueOf(classification.getMode().toUpperCase())); } catch(DomainException e) { throw new ServiceException( "There was a problem reading the classification's information.", e); } } // If the features don't exist, then create the classifier data // with only the mode. else { try { mobilityPoint.setClassifierModeOnly(MobilityPoint.Mode.valueOf(classification.getMode().toUpperCase())); } catch(DomainException e) { throw new ServiceException( "There was a problem reading the classification's mode.", e); } } } } } /** * Retrieves the information about all of the Mobility points that satisfy * the parameters. The username is required as that is how Mobility points * are referenced; however, all other parameters are optional and limit the * results based on their value.<br /> * <br /> * For example, if only a username is given, the result is all of the * Mobility points for that user. If the username and start date are given, * then all of the Mobility points made by that user after that date are * returned. If the username, start date, and end date are all given, the * result is the list of Mobility points made by that user on or after the * start date and on or before the end date. * * @param username The username of the user whose points are being queried. * Required. * * @param startDate A date to which all returned points must be on or * after. Optional. * * @param endDate A date to which all returned points must be on or before. * Optional. * * @param privacyState A privacy state to limit the results to only those * with this privacy state. Optional. * * @param locationStatus A location status to limit the results to only * those with this location status. Optional. * * @param mode A mode to limit the results to only those with this mode. * Optional. * * @return A list of MobilityInformation objects where each object * represents a single Mobility point that satisfies the * parameters. * * @throws ServiceException Thrown if there is an error. */ public List<MobilityPoint> retrieveMobilityData( final String username, final DateTime startDate, final DateTime endDate, final MobilityPoint.PrivacyState privacyState, final LocationStatus locationStatus, final Mode mode) throws ServiceException { try { return userMobilityQueries.getMobilityInformation( username, startDate, endDate, privacyState, locationStatus, mode); } catch(DataAccessException e) { throw new ServiceException(e); } } /** * Retrieves all of the dates on which the user has created a Mobility * point within the date range. * * @param startDate The earliest date to check if the user has any Mobility * points. * * @param endDate The latest date to check if the user has any Mobility * points. * * @param username The user's username. * * @return A collection of all of the dates. * * @throws ServiceException Thrown if there is an error. */ public Collection<DateTime> getDates( final DateTime startDate, final DateTime endDate, final String username) throws ServiceException { try { return userMobilityQueries.getDates(startDate, endDate, username); } catch(DataAccessException e) { throw new ServiceException(e); } } }
false
true
public void classifyData( final String uploadersUsername, final List<MobilityPoint> mobilityPoints) throws ServiceException { // If the list is empty, just exit. if(mobilityPoints == null) { return; } // Create a new classifier. MobilityClassifier classifier = new MobilityClassifier(); // Create place holders for the previous data. String previousWifiMode = null; List<WifiScan> previousWifiScans = new LinkedList<WifiScan>(); if(mobilityPoints.size() > 0) { try { DateTime startDate = new DateTime(); startDate = new DateTime( mobilityPoints.get(0).getTime() - MAX_MILLIS_OF_PREVIOUS_WIFI_DATA); List<MobilityPoint> previousPoints = userMobilityQueries.getMobilityInformation( uploadersUsername, startDate, null, null, null, null); for(MobilityPoint previousPoint : previousPoints) { try { previousWifiScans.add(previousPoint.getWifiScan()); } catch(DomainException e) { // This point does not have a WifiScan, so we will skip // it. } } } catch(DataAccessException e) { throw new ServiceException(e); } } // For each of the Mobility points, for(MobilityPoint mobilityPoint : mobilityPoints) { // If the data point is of type error, don't attempt to classify // it. if(mobilityPoint.getMode().equals(Mode.ERROR)) { continue; } // If the SubType is sensor data, if(MobilityPoint.SubType.SENSOR_DATA.equals(mobilityPoint.getSubType())) { SensorData currSensorData = mobilityPoint.getSensorData(); // Get the Samples from this new point. List<Sample> samples; try { samples = mobilityPoint.getSamples(); } catch(DomainException e) { throw new ServiceException( "There was a problem retrieving the samples.", e); } // Get the new WifiScan from this new point. WifiScan wifiScan; if(mobilityPoint.getSensorData().getWifiData() == null) { wifiScan = null; } else { try { wifiScan = mobilityPoint.getWifiScan(); } catch(DomainException e) { throw new ServiceException( "The Mobility point does not contain WiFi data.", e); } } // Prune out the old WifiScans that are more than 10 minutes // old. long minPreviousTime = mobilityPoint.getTime() - MAX_MILLIS_OF_PREVIOUS_WIFI_DATA; Iterator<WifiScan> previousWifiScansIter = previousWifiScans.iterator(); while(previousWifiScansIter.hasNext()) { if(previousWifiScansIter.next().getTime() < minPreviousTime) { previousWifiScansIter.remove(); } else { // Given the fact that the list is ordered, we can now // be assured that all of the remaining WiFi scans are // invalid. break; } } // Classify the data. Classification classification = classifier.classify( samples, currSensorData.getSpeed(), wifiScan, previousWifiScans, previousWifiMode); // Update the place holders for the previous data. if(wifiScan != null) { previousWifiScans.add(wifiScan); } previousWifiMode = classification.getWifiMode(); // If the classification generated some results, pull them out // and store them in the Mobility point. if(classification.hasFeatures()) { try { mobilityPoint.setClassifierData( classification.getFft(), classification.getVariance(), classification.getAverage(), MobilityPoint.Mode.valueOf(classification.getMode().toUpperCase())); } catch(DomainException e) { throw new ServiceException( "There was a problem reading the classification's information.", e); } } // If the features don't exist, then create the classifier data // with only the mode. else { try { mobilityPoint.setClassifierModeOnly(MobilityPoint.Mode.valueOf(classification.getMode().toUpperCase())); } catch(DomainException e) { throw new ServiceException( "There was a problem reading the classification's mode.", e); } } } } }
public void classifyData( final String uploadersUsername, final List<MobilityPoint> mobilityPoints) throws ServiceException { // If the list is empty, just exit. if(mobilityPoints == null) { return; } // Create a new classifier. MobilityClassifier classifier = new MobilityClassifier(); // Create place holders for the previous data. String previousWifiMode = null; List<WifiScan> previousWifiScans = new LinkedList<WifiScan>(); if(mobilityPoints.size() > 0) { try { MobilityPoint firstPoint = mobilityPoints.get(0); DateTime startDate = new DateTime(); startDate = new DateTime( firstPoint.getTime() - MAX_MILLIS_OF_PREVIOUS_WIFI_DATA); List<MobilityPoint> previousPoints = userMobilityQueries.getMobilityInformation( uploadersUsername, startDate, new DateTime(firstPoint.getTime()), null, null, null); for(MobilityPoint previousPoint : previousPoints) { try { previousWifiScans.add(previousPoint.getWifiScan()); } catch(DomainException e) { // This point does not have a WifiScan, so we will skip // it. } } } catch(DataAccessException e) { throw new ServiceException(e); } } // For each of the Mobility points, for(MobilityPoint mobilityPoint : mobilityPoints) { // If the data point is of type error, don't attempt to classify // it. if(mobilityPoint.getMode().equals(Mode.ERROR)) { continue; } // If the SubType is sensor data, if(MobilityPoint.SubType.SENSOR_DATA.equals(mobilityPoint.getSubType())) { SensorData currSensorData = mobilityPoint.getSensorData(); // Get the Samples from this new point. List<Sample> samples; try { samples = mobilityPoint.getSamples(); } catch(DomainException e) { throw new ServiceException( "There was a problem retrieving the samples.", e); } // Get the new WifiScan from this new point. WifiScan wifiScan; if(mobilityPoint.getSensorData().getWifiData() == null) { wifiScan = null; } else { try { wifiScan = mobilityPoint.getWifiScan(); } catch(DomainException e) { throw new ServiceException( "The Mobility point does not contain WiFi data.", e); } } // Prune out the old WifiScans that are more than 10 minutes // old. long minPreviousTime = mobilityPoint.getTime() - MAX_MILLIS_OF_PREVIOUS_WIFI_DATA; Iterator<WifiScan> previousWifiScansIter = previousWifiScans.iterator(); while(previousWifiScansIter.hasNext()) { if(previousWifiScansIter.next().getTime() < minPreviousTime) { previousWifiScansIter.remove(); } else { // Given the fact that the list is ordered, we can now // be assured that all of the remaining WiFi scans are // invalid. break; } } // Classify the data. Classification classification = classifier.classify( samples, currSensorData.getSpeed(), wifiScan, previousWifiScans, previousWifiMode); // Update the place holders for the previous data. if(wifiScan != null) { previousWifiScans.add(wifiScan); } previousWifiMode = classification.getWifiMode(); // If the classification generated some results, pull them out // and store them in the Mobility point. if(classification.hasFeatures()) { try { mobilityPoint.setClassifierData( classification.getFft(), classification.getVariance(), classification.getAverage(), MobilityPoint.Mode.valueOf(classification.getMode().toUpperCase())); } catch(DomainException e) { throw new ServiceException( "There was a problem reading the classification's information.", e); } } // If the features don't exist, then create the classifier data // with only the mode. else { try { mobilityPoint.setClassifierModeOnly(MobilityPoint.Mode.valueOf(classification.getMode().toUpperCase())); } catch(DomainException e) { throw new ServiceException( "There was a problem reading the classification's mode.", e); } } } } }
diff --git a/java/telehash-core/src/main/java/org/telehash/SeeHandler.java b/java/telehash-core/src/main/java/org/telehash/SeeHandler.java index 69a2c71..b5d577a 100644 --- a/java/telehash-core/src/main/java/org/telehash/SeeHandler.java +++ b/java/telehash-core/src/main/java/org/telehash/SeeHandler.java @@ -1,92 +1,92 @@ package org.telehash; import java.net.InetSocketAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.telehash.model.Line; import org.telehash.model.TelehashFactory; import org.telehash.model.TelehashPackage; import org.telehash.model.Telex; public class SeeHandler implements TelexHandler { static private Logger logger = LoggerFactory.getLogger(SeeHandler.class); static private TelehashFactory tf = TelehashFactory.eINSTANCE; @Override public boolean isMatch(Telex telex) { return telex.isSetSee(); } @Override public void telexReceived(SwitchHandler switchHandler, Line line, Telex telex) { SeeCommandHandler command = new SeeCommandHandler(switchHandler, line, telex); command.execute(); } private class SeeCommandHandler { private SwitchHandler switchHandler; private Line recvLine; private Telex telex; private SeeCommandHandler(SwitchHandler switchHandler, Line line, Telex telex) { this.switchHandler = switchHandler; this.recvLine = line; this.telex = telex; } public void execute() { logger.debug("BEGIN .see HANDLER"); for (InetSocketAddress seeAddr : telex.getSee()) { if (seeAddr.equals(switchHandler.getAddress())) { continue; } // they're making themselves visible now, awesome if (seeAddr.equals(recvLine.getAddress()) && !recvLine.isVisible()) { logger.debug("VISIBLE " + recvLine.getAddress()); recvLine.setVisible(true); recvLine.getNeighbors().addAll( switchHandler.nearTo(recvLine.getEnd(), switchHandler.getAddress())); - switchHandler.nearTo(recvLine.getEnd(), recvLine.getAddress()); // injects this switch as hints into it's neighbors, fully seeded now + switchHandler.nearTo(recvLine.getEnd(), recvLine.getAddress()); // injects this switch as hints into its neighbors, fully seeded now } Hash seeHash = Hash.of(seeAddr); if (switchHandler.getLine(seeHash) != null) { continue; } // XXX todo: if we're dialing we'd want to reach out to any of these closer to that $tap_end // also check to see if we want them in a bucket if (bucketWant(seeAddr, seeHash)) { // send direct (should open our outgoing to them) Telex telexOut = tf.createTelex().withTo(seeAddr) .withEnd(switchHandler.getAddressHash()); switchHandler.send(telexOut); // send pop signal back to the switch who .see'd us in case the new one is behind a nat telexOut = (Telex) tf.createTelex().withTo(recvLine) .withEnd(seeHash) .with("+pop", "th:" + tf.convertToString(TelehashPackage.Literals.ENDPOINT, switchHandler.getAddress())) .with("_hop", 1); switchHandler.send(telexOut); } } logger.debug("END .see HANDLER"); } private boolean bucketWant(InetSocketAddress seeAddr, Hash seeHash) { int dist = seeHash.diffBit(switchHandler.getAddressHash()); logger.debug("BUCKET WANT[{} -> {} -> {}]", new Object[]{ seeAddr, Integer.toString(dist), switchHandler.getAddress()}); return dist >= 0; } } }
true
true
public void execute() { logger.debug("BEGIN .see HANDLER"); for (InetSocketAddress seeAddr : telex.getSee()) { if (seeAddr.equals(switchHandler.getAddress())) { continue; } // they're making themselves visible now, awesome if (seeAddr.equals(recvLine.getAddress()) && !recvLine.isVisible()) { logger.debug("VISIBLE " + recvLine.getAddress()); recvLine.setVisible(true); recvLine.getNeighbors().addAll( switchHandler.nearTo(recvLine.getEnd(), switchHandler.getAddress())); switchHandler.nearTo(recvLine.getEnd(), recvLine.getAddress()); // injects this switch as hints into it's neighbors, fully seeded now } Hash seeHash = Hash.of(seeAddr); if (switchHandler.getLine(seeHash) != null) { continue; } // XXX todo: if we're dialing we'd want to reach out to any of these closer to that $tap_end // also check to see if we want them in a bucket if (bucketWant(seeAddr, seeHash)) { // send direct (should open our outgoing to them) Telex telexOut = tf.createTelex().withTo(seeAddr) .withEnd(switchHandler.getAddressHash()); switchHandler.send(telexOut); // send pop signal back to the switch who .see'd us in case the new one is behind a nat telexOut = (Telex) tf.createTelex().withTo(recvLine) .withEnd(seeHash) .with("+pop", "th:" + tf.convertToString(TelehashPackage.Literals.ENDPOINT, switchHandler.getAddress())) .with("_hop", 1); switchHandler.send(telexOut); } } logger.debug("END .see HANDLER"); }
public void execute() { logger.debug("BEGIN .see HANDLER"); for (InetSocketAddress seeAddr : telex.getSee()) { if (seeAddr.equals(switchHandler.getAddress())) { continue; } // they're making themselves visible now, awesome if (seeAddr.equals(recvLine.getAddress()) && !recvLine.isVisible()) { logger.debug("VISIBLE " + recvLine.getAddress()); recvLine.setVisible(true); recvLine.getNeighbors().addAll( switchHandler.nearTo(recvLine.getEnd(), switchHandler.getAddress())); switchHandler.nearTo(recvLine.getEnd(), recvLine.getAddress()); // injects this switch as hints into its neighbors, fully seeded now } Hash seeHash = Hash.of(seeAddr); if (switchHandler.getLine(seeHash) != null) { continue; } // XXX todo: if we're dialing we'd want to reach out to any of these closer to that $tap_end // also check to see if we want them in a bucket if (bucketWant(seeAddr, seeHash)) { // send direct (should open our outgoing to them) Telex telexOut = tf.createTelex().withTo(seeAddr) .withEnd(switchHandler.getAddressHash()); switchHandler.send(telexOut); // send pop signal back to the switch who .see'd us in case the new one is behind a nat telexOut = (Telex) tf.createTelex().withTo(recvLine) .withEnd(seeHash) .with("+pop", "th:" + tf.convertToString(TelehashPackage.Literals.ENDPOINT, switchHandler.getAddress())) .with("_hop", 1); switchHandler.send(telexOut); } } logger.debug("END .see HANDLER"); }
diff --git a/Java_CCN/test/ccn/data/query/InterestEndToEndTest.java b/Java_CCN/test/ccn/data/query/InterestEndToEndTest.java index 5c1e82637..8a62873f5 100644 --- a/Java_CCN/test/ccn/data/query/InterestEndToEndTest.java +++ b/Java_CCN/test/ccn/data/query/InterestEndToEndTest.java @@ -1,66 +1,69 @@ package test.ccn.data.query; import java.io.IOException; import java.util.ArrayList; import org.junit.Assert; import org.junit.Test; import test.ccn.library.LibraryTestBase; import com.parc.ccn.data.ContentName; import com.parc.ccn.data.ContentObject; import com.parc.ccn.data.MalformedContentNameStringException; import com.parc.ccn.data.query.CCNFilterListener; import com.parc.ccn.data.query.CCNInterestListener; import com.parc.ccn.data.query.Interest; /** * Test sending interests across ccnd * Requires a running ccnd * * @author rasmusse * */ public class InterestEndToEndTest extends LibraryTestBase implements CCNFilterListener, CCNInterestListener { private Interest _interestSent; private String _prefix = "/interestEtoETest/test-" + rand.nextInt(10000); private final static int TIMEOUT = 3000; @Test public void testInterestEndToEnd() throws MalformedContentNameStringException, IOException, InterruptedException { getLibrary.registerFilter(ContentName.fromNative(_prefix), this); _interestSent = new Interest(ContentName.fromNative(_prefix + "/simpleTest")); doTest(); _interestSent = new Interest(ContentName.fromNative(_prefix + "/simpleTest2")); - _interestSent.maxSuffixComponents(3); - _interestSent.minSuffixComponents(4); + _interestSent.maxSuffixComponents(4); + _interestSent.minSuffixComponents(3); + doTest(); + _interestSent = new Interest(ContentName.fromNative(_prefix + "/simpleTest2")); + _interestSent.maxSuffixComponents(1); doTest(); } public int handleInterests(ArrayList<Interest> interests) { Assert.assertTrue(_interestSent.equals(interests.get(0))); synchronized(this) { notify(); } return 0; } private void doTest() throws IOException, InterruptedException { long startTime = System.currentTimeMillis(); putLibrary.expressInterest(_interestSent, this); synchronized (this) { wait(TIMEOUT); } Assert.assertTrue((System.currentTimeMillis() - startTime) < TIMEOUT); } public Interest handleContent(ArrayList<ContentObject> results, Interest interest) { // TODO Auto-generated method stub return null; } }
true
true
public void testInterestEndToEnd() throws MalformedContentNameStringException, IOException, InterruptedException { getLibrary.registerFilter(ContentName.fromNative(_prefix), this); _interestSent = new Interest(ContentName.fromNative(_prefix + "/simpleTest")); doTest(); _interestSent = new Interest(ContentName.fromNative(_prefix + "/simpleTest2")); _interestSent.maxSuffixComponents(3); _interestSent.minSuffixComponents(4); doTest(); }
public void testInterestEndToEnd() throws MalformedContentNameStringException, IOException, InterruptedException { getLibrary.registerFilter(ContentName.fromNative(_prefix), this); _interestSent = new Interest(ContentName.fromNative(_prefix + "/simpleTest")); doTest(); _interestSent = new Interest(ContentName.fromNative(_prefix + "/simpleTest2")); _interestSent.maxSuffixComponents(4); _interestSent.minSuffixComponents(3); doTest(); _interestSent = new Interest(ContentName.fromNative(_prefix + "/simpleTest2")); _interestSent.maxSuffixComponents(1); doTest(); }
diff --git a/src/a2/Lookup.java b/src/a2/Lookup.java index a3ebd84..4dc213e 100644 --- a/src/a2/Lookup.java +++ b/src/a2/Lookup.java @@ -1,42 +1,46 @@ package a2; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.IOUtils; import au.com.bytecode.opencsv.CSVReader; public class Lookup { public static void main(String args[]) throws IOException{ Map<Integer,Integer> vals = get(); System.out.println(vals.get(24)); } public static HashMap<Integer,Integer> get(){ HashMap<Integer,Integer> ret = new HashMap<Integer,Integer>(); CSVReader reader = null; try{ - reader = new CSVReader(new InputStreamReader(new Lookup().getClass().getClassLoader() + reader = new CSVReader( + new InputStreamReader( + new Lookup() + .getClass() + .getClassLoader() .getResourceAsStream("resources/lookup.csv"))); String [] nextLine; int i = 0; while ((nextLine = reader.readNext()) != null) { i++; String id = nextLine[0]; String count = nextLine[1]; ret.put(Integer.parseInt(id),Integer.parseInt(count)); } }catch(IOException e){ e.printStackTrace(System.err); }finally{ IOUtils.closeQuietly(reader); } return ret; } }
true
true
public static HashMap<Integer,Integer> get(){ HashMap<Integer,Integer> ret = new HashMap<Integer,Integer>(); CSVReader reader = null; try{ reader = new CSVReader(new InputStreamReader(new Lookup().getClass().getClassLoader() .getResourceAsStream("resources/lookup.csv"))); String [] nextLine; int i = 0; while ((nextLine = reader.readNext()) != null) { i++; String id = nextLine[0]; String count = nextLine[1]; ret.put(Integer.parseInt(id),Integer.parseInt(count)); } }catch(IOException e){ e.printStackTrace(System.err); }finally{ IOUtils.closeQuietly(reader); } return ret; }
public static HashMap<Integer,Integer> get(){ HashMap<Integer,Integer> ret = new HashMap<Integer,Integer>(); CSVReader reader = null; try{ reader = new CSVReader( new InputStreamReader( new Lookup() .getClass() .getClassLoader() .getResourceAsStream("resources/lookup.csv"))); String [] nextLine; int i = 0; while ((nextLine = reader.readNext()) != null) { i++; String id = nextLine[0]; String count = nextLine[1]; ret.put(Integer.parseInt(id),Integer.parseInt(count)); } }catch(IOException e){ e.printStackTrace(System.err); }finally{ IOUtils.closeQuietly(reader); } return ret; }
diff --git a/tests/src/com/android/providers/contacts/GlobalSearchSupportTest.java b/tests/src/com/android/providers/contacts/GlobalSearchSupportTest.java index 40ac1bab..066c47e8 100644 --- a/tests/src/com/android/providers/contacts/GlobalSearchSupportTest.java +++ b/tests/src/com/android/providers/contacts/GlobalSearchSupportTest.java @@ -1,397 +1,397 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.providers.contacts; import android.accounts.Account; import android.app.SearchManager; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Intents; import android.provider.ContactsContract.StatusUpdates; import android.test.suitebuilder.annotation.LargeTest; /** * Unit tests for {@link GlobalSearchSupport}. * <p> * Run the test like this: * <p> * <code><pre> * adb shell am instrument -e class com.android.providers.contacts.GlobalSearchSupportTest -w \ * com.android.providers.contacts.tests/android.test.InstrumentationTestRunner * </pre></code> */ @LargeTest public class GlobalSearchSupportTest extends BaseContactsProvider2Test { public void testSearchSuggestionsNotInDefaultDirectory() throws Exception { Account account = new Account("actname", "acttype"); // Creating an AUTO_ADD group will exclude all ungrouped contacts from global search createGroup(account, "any", "any", 0 /* visible */, true /* auto-add */, false /* fav */); long rawContactId = createRawContact(account); insertStructuredName(rawContactId, "Deer", "Dough"); // Remove the new contact from all groups mResolver.delete(Data.CONTENT_URI, Data.RAW_CONTACT_ID + "=" + rawContactId + " AND " + Data.MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE + "'", null); Uri searchUri = new Uri.Builder().scheme("content").authority(ContactsContract.AUTHORITY) .appendPath(SearchManager.SUGGEST_URI_PATH_QUERY).appendPath("D").build(); // If the contact is not in the "my contacts" group, nothing should be found Cursor c = mResolver.query(searchUri, null, null, null, null); assertEquals(0, c.getCount()); c.close(); } public void testSearchSuggestionsByNameWithPhoto() throws Exception { GoldenContact contact = new GoldenContactBuilder().name("Deer", "Dough").photo( loadTestPhoto()).build(); new SuggestionTesterBuilder(contact).query("D").expectIcon1Uri(true).expectedText1( "Deer Dough").build().test(); } public void testSearchSuggestionsByEmailWithPhoto() { GoldenContact contact = new GoldenContactBuilder().name("Deer", "Dough").photo( loadTestPhoto()).email("[email protected]").build(); new SuggestionTesterBuilder(contact).query("foo@ac").expectIcon1Uri(true).expectedIcon2( String.valueOf(StatusUpdates.getPresenceIconResourceId(StatusUpdates.OFFLINE))) .expectedText1("Deer Dough").expectedText2("[email protected]").build().test(); } public void testSearchSuggestionsByName() { GoldenContact contact = new GoldenContactBuilder().name("Deer", "Dough").company("Google") .build(); new SuggestionTesterBuilder(contact).query("D").expectedText1("Deer Dough").expectedText2( null).build().test(); } public void testSearchByNickname() { GoldenContact contact = new GoldenContactBuilder().name("Deer", "Dough").nickname( "Little Fawn").company("Google").build(); new SuggestionTesterBuilder(contact).query("L").expectedText1("Deer Dough").expectedText2( "Little Fawn").build().test(); } public void testSearchByCompany() { GoldenContact contact = new GoldenContactBuilder().name("Deer", "Dough").company("Google") .build(); new SuggestionTesterBuilder(contact).query("G").expectedText1("Deer Dough").expectedText2( "Google").build().test(); } public void testSearchByTitleWithCompany() { GoldenContact contact = new GoldenContactBuilder().name("Deer", "Dough").company("Google") .title("Software Engineer").build(); new SuggestionTesterBuilder(contact).query("S").expectIcon1Uri(false).expectedText1( "Deer Dough").expectedText2("Software Engineer, Google").build().test(); } public void testSearchSuggestionsByPhoneNumberOnNonPhone() throws Exception { getContactsProvider().setIsPhone(false); GoldenContact contact = new GoldenContactBuilder().name("Deer", "Dough").photo( loadTestPhoto()).phone("1-800-4664-411").build(); new SuggestionTesterBuilder(contact).query("1800").expectIcon1Uri(true).expectedText1( "Deer Dough").expectedText2("1-800-4664-411").build().test(); } public void testSearchSuggestionsByPhoneNumberOnPhone() throws Exception { getContactsProvider().setIsPhone(true); ContentValues values = new ContentValues(); Uri searchUri = new Uri.Builder().scheme("content").authority(ContactsContract.AUTHORITY) - .appendPath(SearchManager.SUGGEST_URI_PATH_QUERY).appendPath("12345").build(); + .appendPath(SearchManager.SUGGEST_URI_PATH_QUERY).appendPath("12345678").build(); Cursor c = mResolver.query(searchUri, null, null, null, null); assertEquals(2, c.getCount()); c.moveToFirst(); values.put(SearchManager.SUGGEST_COLUMN_TEXT_1, "Dial number"); - values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, "using 12345"); + values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, "using 12345678"); values.put(SearchManager.SUGGEST_COLUMN_ICON_1, String.valueOf(com.android.internal.R.drawable.call_contact)); values.put(SearchManager.SUGGEST_COLUMN_INTENT_ACTION, Intents.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED); - values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, "tel:12345"); + values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, "tel:12345678"); values.putNull(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID); assertCursorValues(c, values); c.moveToNext(); values.clear(); values.put(SearchManager.SUGGEST_COLUMN_TEXT_1, "Create contact"); - values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, "using 12345"); + values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, "using 12345678"); values.put(SearchManager.SUGGEST_COLUMN_ICON_1, String.valueOf(com.android.internal.R.drawable.create_contact)); values.put(SearchManager.SUGGEST_COLUMN_INTENT_ACTION, Intents.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED); - values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, "tel:12345"); + values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, "tel:12345678"); values.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, SearchManager.SUGGEST_NEVER_MAKE_SHORTCUT); assertCursorValues(c, values); c.close(); } /** * Tests that the quick search suggestion returns the expected contact * information. */ private final class SuggestionTester { private final GoldenContact contact; private final String query; private final boolean expectIcon1Uri; private final String expectedIcon2; private final String expectedText1; private final String expectedText2; public SuggestionTester(SuggestionTesterBuilder builder) { contact = builder.contact; query = builder.query; expectIcon1Uri = builder.expectIcon1Uri; expectedIcon2 = builder.expectedIcon2; expectedText1 = builder.expectedText1; expectedText2 = builder.expectedText2; } /** * Tests suggest and refresh queries from quick search box, then deletes the contact from * the data base. */ public void test() { testQsbSuggest(); testContactIdQsbRefresh(); testLookupKeyQsbRefresh(); // Cleanup contact.delete(); } /** * Tests that the contacts provider return the appropriate information from the golden * contact in response to the suggestion query from the quick search box. */ private void testQsbSuggest() { Uri searchUri = new Uri.Builder().scheme("content").authority( ContactsContract.AUTHORITY).appendPath(SearchManager.SUGGEST_URI_PATH_QUERY) .appendPath(query).build(); Cursor c = mResolver.query(searchUri, null, null, null, null); assertEquals(1, c.getCount()); c.moveToFirst(); String icon1 = c.getString(c.getColumnIndex(SearchManager.SUGGEST_COLUMN_ICON_1)); if (expectIcon1Uri) { assertTrue(icon1.startsWith("content:")); } else { assertEquals(String.valueOf(com.android.internal.R.drawable.ic_contact_picture), icon1); } // SearchManager does not declare a constant for _id ContentValues values = getContactValues(); assertCursorValues(c, values); c.close(); } /** * Returns the expected Quick Search Box content values for the golden contact. */ private ContentValues getContactValues() { ContentValues values = new ContentValues(); values.put("_id", contact.getContactId()); values.put(SearchManager.SUGGEST_COLUMN_TEXT_1, expectedText1); values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, expectedText2); values.put(SearchManager.SUGGEST_COLUMN_ICON_2, expectedIcon2); values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, Contacts.getLookupUri(contact.getContactId(), contact.getLookupKey()) .toString()); values.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, contact.getLookupKey()); values.put(SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA, query); return values; } /** * Returns the expected Quick Search Box content values for the golden contact. */ private ContentValues getRefreshValues() { ContentValues values = new ContentValues(); values.put("_id", contact.getContactId()); values.put(SearchManager.SUGGEST_COLUMN_TEXT_1, expectedText1); values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, expectedText2); values.put(SearchManager.SUGGEST_COLUMN_ICON_2, expectedIcon2); values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID, contact.getLookupKey()); values.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, contact.getLookupKey()); return values; } /** * Performs the refresh query and returns a cursor to the results. * * @param refreshId the final component path of the refresh query, which identifies which * contact to refresh. */ private Cursor refreshQuery(String refreshId) { // See if the same result is returned by a shortcut refresh Uri refershUri = ContactsContract.AUTHORITY_URI.buildUpon().appendPath( SearchManager.SUGGEST_URI_PATH_SHORTCUT) .appendPath(refreshId) .appendQueryParameter(SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA, query) .build(); String[] projection = new String[] { SearchManager.SUGGEST_COLUMN_ICON_1, SearchManager.SUGGEST_COLUMN_ICON_2, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_TEXT_2, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID, SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, "_id", }; return mResolver.query(refershUri, projection, null, null, null); } /** * Tests that the contacts provider returns an empty result in response to a refresh query * from the quick search box that uses the contact id to identify the contact. The empty * result indicates that the shortcut is no longer valid, and the QSB will replace it with * a new-style shortcut the next time they click on the contact. * * @see #testLookupKeyQsbRefresh() */ private void testContactIdQsbRefresh() { Cursor c = refreshQuery(String.valueOf(contact.getContactId())); try { assertEquals("Record count", 0, c.getCount()); } finally { c.close(); } } /** * Tests that the contacts provider return the appropriate information from the golden * contact in response to the refresh query from the quick search box. The refresh query * uses the currently-supported mechanism of identifying the contact by the lookup key, * which is more stable than the previously used contact id. */ private void testLookupKeyQsbRefresh() { Cursor c = refreshQuery(contact.getLookupKey()); try { assertEquals("Record count", 1, c.getCount()); c.moveToFirst(); assertCursorValues(c, getRefreshValues()); } finally { c.close(); } } } /** * Builds {@link SuggestionTester} objects. Unspecified boolean objects default to * false. Unspecified String objects default to null. */ private final class SuggestionTesterBuilder { private final GoldenContact contact; private String query; private boolean expectIcon1Uri; private String expectedIcon2; private String expectedText1; private String expectedText2; public SuggestionTesterBuilder(GoldenContact contact) { this.contact = contact; } /** * Builds the {@link SuggestionTester} specified by this builder. */ public SuggestionTester build() { return new SuggestionTester(this); } /** * The text of the user's query to quick search (i.e., what they typed * in the search box). */ public SuggestionTesterBuilder query(String value) { query = value; return this; } /** * Whether to set Icon1, which in practice is the contact's photo. * <p> * TODO(tomo): Replace with actual expected value? This might be hard * because the values look non-deterministic, such as * "content://com.android.contacts/contacts/2015/photo" */ public SuggestionTesterBuilder expectIcon1Uri(boolean value) { expectIcon1Uri = value; return this; } /** * The value for Icon2, which in practice is the contact's Chat status * (available, busy, etc.) */ public SuggestionTesterBuilder expectedIcon2(String value) { expectedIcon2 = value; return this; } /** * First line of suggestion text expected to be returned (required). */ public SuggestionTesterBuilder expectedText1(String value) { expectedText1 = value; return this; } /** * Second line of suggestion text expected to return (optional). */ public SuggestionTesterBuilder expectedText2(String value) { expectedText2 = value; return this; } } }
false
true
public void testSearchSuggestionsByPhoneNumberOnPhone() throws Exception { getContactsProvider().setIsPhone(true); ContentValues values = new ContentValues(); Uri searchUri = new Uri.Builder().scheme("content").authority(ContactsContract.AUTHORITY) .appendPath(SearchManager.SUGGEST_URI_PATH_QUERY).appendPath("12345").build(); Cursor c = mResolver.query(searchUri, null, null, null, null); assertEquals(2, c.getCount()); c.moveToFirst(); values.put(SearchManager.SUGGEST_COLUMN_TEXT_1, "Dial number"); values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, "using 12345"); values.put(SearchManager.SUGGEST_COLUMN_ICON_1, String.valueOf(com.android.internal.R.drawable.call_contact)); values.put(SearchManager.SUGGEST_COLUMN_INTENT_ACTION, Intents.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED); values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, "tel:12345"); values.putNull(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID); assertCursorValues(c, values); c.moveToNext(); values.clear(); values.put(SearchManager.SUGGEST_COLUMN_TEXT_1, "Create contact"); values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, "using 12345"); values.put(SearchManager.SUGGEST_COLUMN_ICON_1, String.valueOf(com.android.internal.R.drawable.create_contact)); values.put(SearchManager.SUGGEST_COLUMN_INTENT_ACTION, Intents.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED); values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, "tel:12345"); values.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, SearchManager.SUGGEST_NEVER_MAKE_SHORTCUT); assertCursorValues(c, values); c.close(); }
public void testSearchSuggestionsByPhoneNumberOnPhone() throws Exception { getContactsProvider().setIsPhone(true); ContentValues values = new ContentValues(); Uri searchUri = new Uri.Builder().scheme("content").authority(ContactsContract.AUTHORITY) .appendPath(SearchManager.SUGGEST_URI_PATH_QUERY).appendPath("12345678").build(); Cursor c = mResolver.query(searchUri, null, null, null, null); assertEquals(2, c.getCount()); c.moveToFirst(); values.put(SearchManager.SUGGEST_COLUMN_TEXT_1, "Dial number"); values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, "using 12345678"); values.put(SearchManager.SUGGEST_COLUMN_ICON_1, String.valueOf(com.android.internal.R.drawable.call_contact)); values.put(SearchManager.SUGGEST_COLUMN_INTENT_ACTION, Intents.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED); values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, "tel:12345678"); values.putNull(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID); assertCursorValues(c, values); c.moveToNext(); values.clear(); values.put(SearchManager.SUGGEST_COLUMN_TEXT_1, "Create contact"); values.put(SearchManager.SUGGEST_COLUMN_TEXT_2, "using 12345678"); values.put(SearchManager.SUGGEST_COLUMN_ICON_1, String.valueOf(com.android.internal.R.drawable.create_contact)); values.put(SearchManager.SUGGEST_COLUMN_INTENT_ACTION, Intents.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED); values.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA, "tel:12345678"); values.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, SearchManager.SUGGEST_NEVER_MAKE_SHORTCUT); assertCursorValues(c, values); c.close(); }
diff --git a/webbeans-ri/src/main/java/org/jboss/webbeans/introspector/AnnotatedType.java b/webbeans-ri/src/main/java/org/jboss/webbeans/introspector/AnnotatedType.java index 7a306395a..6a58b1bee 100644 --- a/webbeans-ri/src/main/java/org/jboss/webbeans/introspector/AnnotatedType.java +++ b/webbeans-ri/src/main/java/org/jboss/webbeans/introspector/AnnotatedType.java @@ -1,44 +1,44 @@ /* * JBoss, Home of Professional Open Source * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.webbeans.introspector; /** * AnnotatedType provides a uniform access to a type defined either in Java or * XML * * @author Pete Muir * @param <T> */ public interface AnnotatedType<T> extends AnnotatedItem<T, Class<T>> { /** * Gets the superclass of the type * * @return The abstracted superclass */ - public AnnotatedType<Object> getSuperclass(); + public AnnotatedType<?> getSuperclass(); /** * Check if this is equivalent to a java class * @param clazz The Java class * @return true if equivalent */ public boolean isEquivalent(Class<?> clazz); }
true
true
public AnnotatedType<Object> getSuperclass();
public AnnotatedType<?> getSuperclass();
diff --git a/org.envirocar.app/src/org/envirocar/app/protocol/drivedeck/DriveDeckSportConnector.java b/org.envirocar.app/src/org/envirocar/app/protocol/drivedeck/DriveDeckSportConnector.java index b917bfe7..0edfa1d8 100644 --- a/org.envirocar.app/src/org/envirocar/app/protocol/drivedeck/DriveDeckSportConnector.java +++ b/org.envirocar.app/src/org/envirocar/app/protocol/drivedeck/DriveDeckSportConnector.java @@ -1,345 +1,348 @@ /* * enviroCar 2013 * Copyright (C) 2013 * Martin Dueren, Jakob Moellers, Gerald Pape, Christopher Stephan * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.envirocar.app.protocol.drivedeck; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import org.envirocar.app.commands.CommonCommand; import org.envirocar.app.commands.IntakePressure; import org.envirocar.app.commands.IntakeTemperature; import org.envirocar.app.commands.MAF; import org.envirocar.app.commands.PIDSupported; import org.envirocar.app.commands.RPM; import org.envirocar.app.commands.CommonCommand.CommonCommandState; import org.envirocar.app.commands.Speed; import org.envirocar.app.logging.Logger; import org.envirocar.app.protocol.AbstractAsynchronousConnector; import org.envirocar.app.protocol.ResponseParser; import org.envirocar.app.protocol.drivedeck.CycleCommand.PID; public class DriveDeckSportConnector extends AbstractAsynchronousConnector { private static final Logger logger = Logger.getLogger(DriveDeckSportConnector.class); private static final char CARRIAGE_RETURN = '\r'; static final char END_OF_LINE_RESPONSE = '>'; private Protocol protocol; private String vin; private long firstConnectionResponse; private CycleCommand cycleCommand; private ResponseParser responseParser = new LocalResponseParser(); private ConnectionState state = ConnectionState.DISCONNECTED; private boolean send; private static enum Protocol { CAN11500, CAN11250, CAN29500, CAN29250, KWP_SLOW, KWP_FAST, ISO9141 } public DriveDeckSportConnector() { createCycleCommand(); logger.info("Static CycleCommand: "+new String(cycleCommand.getOutgoingBytes())); } private void createCycleCommand() { List<PID> pidList = new ArrayList<PID>(); pidList.add(PID.SPEED); pidList.add(PID.MAF); pidList.add(PID.RPM); pidList.add(PID.IAP); pidList.add(PID.IAT); this.cycleCommand = new CycleCommand(pidList); } @Override public ConnectionState connectionState() { return this.state; } private void processDiscoveredControlUnits(String substring) { logger.info("Discovered CUs... "); } private void processSupportedPID(byte[] bytes, int start, int count) { String group = new String(bytes, start+6, 2); if (group.equals("00")) { /* * this is the first group containing the PIDs of major interest */ PIDSupported pidCmd = new PIDSupported(); byte[] rawBytes = new byte[12]; rawBytes[0] = '4'; rawBytes[1] = '1'; rawBytes[2] = (byte) pidCmd.getResponseTypeID().charAt(0); rawBytes[3] = (byte) pidCmd.getResponseTypeID().charAt(1); int target = 4; String hexTmp; for (int i = 9; i < 14; i++) { if (i == 11) continue; hexTmp = oneByteToHex(bytes[i+start]); rawBytes[target++] = (byte) hexTmp.charAt(0); rawBytes[target++] = (byte) hexTmp.charAt(1); } pidCmd.setRawData(rawBytes); pidCmd.parseRawData(); logger.info(pidCmd.getSupportedPIDs().toArray().toString()); } } private String oneByteToHex(byte b) { String result = Integer.toString(b, 16).toUpperCase(Locale.US); if (result.length() == 1) result = "0".concat(result); return result; } private void processVIN(String vinInt) { this.vin = vinInt; logger.info("VIN is: "+this.vin); updateConnectionState(); } private void updateConnectionState() { if (state == ConnectionState.VERIFIED) { return; } if (protocol != null && vin != null) { state = ConnectionState.CONNECTED; } } private void determineProtocol(String protocolInt) { int prot = Integer.parseInt(protocolInt); switch (prot) { case 1: protocol = Protocol.CAN11500; break; case 2: protocol = Protocol.CAN11250; break; case 3: protocol = Protocol.CAN29500; break; case 4: protocol = Protocol.CAN29250; break; case 5: protocol = Protocol.KWP_SLOW; break; case 6: protocol = Protocol.KWP_FAST; break; case 7: protocol = Protocol.ISO9141; break; default: return; } logger.info("Protocol is: "+ protocol.toString()); logger.info("Connected in "+ (System.currentTimeMillis() - firstConnectionResponse) +" ms."); updateConnectionState(); } @Override public boolean supportsDevice(String deviceName) { return deviceName.contains("DRIVEDECK") && deviceName.contains("W4"); } private CommonCommand parsePIDResponse(String pid, byte[] rawBytes, long now) { CommonCommand result = null; if (pid.equals("41")) { //Speed result = new Speed(); } else if (pid.equals("42")) { //MAF result = new MAF(); } else if (pid.equals("52")) { //IAP result = new IntakeTemperature(); } else if (pid.equals("49")) { //IAT result = new IntakePressure(); } else if (pid.equals("40") || pid.equals("51")) { //RPM result = new RPM(); } if (result != null) { byte[] rawData = createRawData(rawBytes, result.getResponseTypeID()); result.setRawData(rawData); result.parseRawData(); result.setCommandState(CommonCommandState.FINISHED); result.setResultTime(now); this.state = ConnectionState.VERIFIED; } return result; } private byte[] createRawData(byte[] rawBytes, String type) { byte[] result = new byte[4 + rawBytes.length*2]; byte[] typeBytes = type.getBytes(); result[0] = (byte) '4'; result[1] = (byte) '1'; result[2] = typeBytes[0]; result[3] = typeBytes[1]; for (int i = 0; i < rawBytes.length; i++) { String hex = byteToHex(rawBytes[i]); result[(i*2)+4] = (byte) hex.charAt(0); result[(i*2)+1+4] = (byte) hex.charAt(1); } return result; } private String byteToHex(byte b) { String result = Integer.toString((int) b, 16); if (result.length() == 1) { result = "0".concat(result); } return result; } @Override protected List<CommonCommand> getRequestCommands() { if (!send) { send = true; return Collections.singletonList((CommonCommand) cycleCommand); } else { return Collections.emptyList(); } } @Override protected char getRequestEndOfLine() { return CARRIAGE_RETURN; } @Override protected ResponseParser getResponseParser() { return responseParser; } @Override protected List<CommonCommand> getInitializationCommands() { try { Thread.sleep(500); } catch (InterruptedException e) { logger.warn(e.getMessage(), e); } return Collections.singletonList((CommonCommand) new CarriageReturnCommand()); } @Override public int getMaximumTriesForInitialization() { return 15; } private class LocalResponseParser implements ResponseParser { @Override public CommonCommand processResponse(byte[] bytes, int start, int count) { if (count <= 0) return null; char type = (char) bytes[start+0]; if (type == CycleCommand.RESPONSE_PREFIX_CHAR) { if ((char) bytes[start+4] == CycleCommand.TOKEN_SEPARATOR_CHAR) return null; String pid = new String(bytes, start+1, 2); /* * METADATA Stuff */ if (pid.equals("14")) { logger.debug("Status: CONNECTING"); } else if (pid.equals("15")) { processVIN(new String(bytes, start+3, count-3)); } else if (pid.equals("70")) { - processSupportedPID(bytes, start, count); + /* + * short term fix for #192: disable + */ +// processSupportedPID(bytes, start, count); } else if (pid.equals("71")) { processDiscoveredControlUnits(new String(bytes, start+3, count-3)); } else { /* * A PID response */ long now = System.currentTimeMillis(); logger.info("Processing PID Response:" +pid); byte[] pidResponseValue = new byte[2]; int target; for (int i = start+4; i <= count+start; i++) { if ((char) bytes[i] == CycleCommand.TOKEN_SEPARATOR_CHAR) break; target = i-(start+4); if (target >= pidResponseValue.length) break; pidResponseValue[target] = bytes[i]; } return parsePIDResponse(pid, pidResponseValue, now); } } else if (type == 'C') { determineProtocol(new String(bytes, start+1, count-1)); } return null; } @Override public char getEndOfLine() { return END_OF_LINE_RESPONSE; } } @Override protected long getSleepTimeBetweenCommands() { return 0; } }
true
true
public CommonCommand processResponse(byte[] bytes, int start, int count) { if (count <= 0) return null; char type = (char) bytes[start+0]; if (type == CycleCommand.RESPONSE_PREFIX_CHAR) { if ((char) bytes[start+4] == CycleCommand.TOKEN_SEPARATOR_CHAR) return null; String pid = new String(bytes, start+1, 2); /* * METADATA Stuff */ if (pid.equals("14")) { logger.debug("Status: CONNECTING"); } else if (pid.equals("15")) { processVIN(new String(bytes, start+3, count-3)); } else if (pid.equals("70")) { processSupportedPID(bytes, start, count); } else if (pid.equals("71")) { processDiscoveredControlUnits(new String(bytes, start+3, count-3)); } else { /* * A PID response */ long now = System.currentTimeMillis(); logger.info("Processing PID Response:" +pid); byte[] pidResponseValue = new byte[2]; int target; for (int i = start+4; i <= count+start; i++) { if ((char) bytes[i] == CycleCommand.TOKEN_SEPARATOR_CHAR) break; target = i-(start+4); if (target >= pidResponseValue.length) break; pidResponseValue[target] = bytes[i]; } return parsePIDResponse(pid, pidResponseValue, now); } } else if (type == 'C') { determineProtocol(new String(bytes, start+1, count-1)); } return null; }
public CommonCommand processResponse(byte[] bytes, int start, int count) { if (count <= 0) return null; char type = (char) bytes[start+0]; if (type == CycleCommand.RESPONSE_PREFIX_CHAR) { if ((char) bytes[start+4] == CycleCommand.TOKEN_SEPARATOR_CHAR) return null; String pid = new String(bytes, start+1, 2); /* * METADATA Stuff */ if (pid.equals("14")) { logger.debug("Status: CONNECTING"); } else if (pid.equals("15")) { processVIN(new String(bytes, start+3, count-3)); } else if (pid.equals("70")) { /* * short term fix for #192: disable */ // processSupportedPID(bytes, start, count); } else if (pid.equals("71")) { processDiscoveredControlUnits(new String(bytes, start+3, count-3)); } else { /* * A PID response */ long now = System.currentTimeMillis(); logger.info("Processing PID Response:" +pid); byte[] pidResponseValue = new byte[2]; int target; for (int i = start+4; i <= count+start; i++) { if ((char) bytes[i] == CycleCommand.TOKEN_SEPARATOR_CHAR) break; target = i-(start+4); if (target >= pidResponseValue.length) break; pidResponseValue[target] = bytes[i]; } return parsePIDResponse(pid, pidResponseValue, now); } } else if (type == 'C') { determineProtocol(new String(bytes, start+1, count-1)); } return null; }
diff --git a/trauma-backend/src/main/java/com/epam/pf/trauma/backend/HomeController.java b/trauma-backend/src/main/java/com/epam/pf/trauma/backend/HomeController.java index 6ccbac8..03a30c1 100644 --- a/trauma-backend/src/main/java/com/epam/pf/trauma/backend/HomeController.java +++ b/trauma-backend/src/main/java/com/epam/pf/trauma/backend/HomeController.java @@ -1,65 +1,65 @@ package com.epam.pf.trauma.backend; import java.util.Collection; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import com.epam.pf.trauma.backend.service.MarkerService; import com.epam.pf.trauma.backend.service.domain.CentralPoint; import com.epam.pf.trauma.backend.service.domain.Marker; /** * Handles requests for the application home page. */ @Controller public class HomeController { private static final Logger LOGGER = LoggerFactory.getLogger(HomeController.class); @Inject private MarkerService markerService; @RequestMapping(value = "/markers", method = RequestMethod.GET, produces = "application/json;charset=UTF-8") @ResponseStatus( HttpStatus.OK ) @ResponseBody - public Collection<Marker> getMarkers(@RequestParam(value = "central-lan", required=false ) float centrallan, @RequestParam(value = "central-lng" ,required=false) float centrallng, - @RequestParam(value = "central-rad", required=false) float centralrad){ - if(centrallan==0) return markerService.getMarkers(); + public Collection<Marker> getMarkers(@RequestParam(value = "central-lan", required=false, defaultValue="999999999") float centrallan, @RequestParam(value = "central-lng" ,required=false,defaultValue="999999999") float centrallng, + @RequestParam(value = "central-rad", required=false,defaultValue="999999999") float centralrad){ + if(centrallan==999999999) return markerService.getMarkers(); else return markerService.getMarkers(new CentralPoint(centrallan, centrallng, centralrad)); } @RequestMapping(value = "/markers/{id}", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8") @ResponseStatus( HttpStatus.OK ) @ResponseBody public void deleteMarker(@PathVariable("id") int id) { markerService.deleteMarker(id); } @RequestMapping(value = "/markers/{id}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseStatus( HttpStatus.OK ) @ResponseBody public Marker editMarker(@PathVariable("id") int id, @RequestBody String desc) { return markerService.editMarker(id, desc); } @RequestMapping(value = "/markers", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8") @ResponseStatus( HttpStatus.CREATED ) @ResponseBody public Marker addMarker(@RequestBody Marker marker) { LOGGER.debug("Marker: {}", marker); return markerService.addMarker(marker); } }
true
true
public Collection<Marker> getMarkers(@RequestParam(value = "central-lan", required=false ) float centrallan, @RequestParam(value = "central-lng" ,required=false) float centrallng, @RequestParam(value = "central-rad", required=false) float centralrad){ if(centrallan==0) return markerService.getMarkers(); else return markerService.getMarkers(new CentralPoint(centrallan, centrallng, centralrad)); }
public Collection<Marker> getMarkers(@RequestParam(value = "central-lan", required=false, defaultValue="999999999") float centrallan, @RequestParam(value = "central-lng" ,required=false,defaultValue="999999999") float centrallng, @RequestParam(value = "central-rad", required=false,defaultValue="999999999") float centralrad){ if(centrallan==999999999) return markerService.getMarkers(); else return markerService.getMarkers(new CentralPoint(centrallan, centrallng, centralrad)); }
diff --git a/source/de/anomic/http/httpdProxyHandler.java b/source/de/anomic/http/httpdProxyHandler.java index dbe1a84f8..56292465b 100644 --- a/source/de/anomic/http/httpdProxyHandler.java +++ b/source/de/anomic/http/httpdProxyHandler.java @@ -1,1308 +1,1321 @@ // httpdProxyHandler.java // ----------------------- // part of YACY // (C) by Michael Peter Christen; [email protected] // first published on http://www.anomic.de // Frankfurt, Germany, 2004 // last major change: 10.05.2004 // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Using this software in any meaning (reading, learning, copying, compiling, // running) means that you agree that the Author(s) is (are) not responsible // for cost, loss of data or any harm that may be caused directly or indirectly // by usage of this softare or this documentation. The usage of this software // is on your own risk. The installation and usage (starting/running) of this // software may allow other people or application to access your computer and // any attached devices and is highly dependent on the configuration of the // software which must be done by the user of the software; the author(s) is // (are) also not responsible for proper configuration and usage of the // software, even if provoked by documentation provided together with // the software. // // Any changes to this file according to the GPL as documented in the file // gpl.txt aside this file in the shipment you received can be done to the // lines that follows this copyright notice here, but changes must not be // done inside the copyright notive above. A re-distribution must contain // the intact and unchanged copyright notice. // Contributions and changes to the program code must be marked as such. // Contributions: // [AS] Alexander Schier: Blacklist (404 response for AGIS hosts) // [TL] Timo Leise: url-wildcards for blacklists /* Class documentation: This class is a servlet to the httpd daemon. It is accessed each time an URL in a GET, HEAD or POST command contains the whole host information or a host is given in the header host field of an HTTP/1.0 / HTTP/1.1 command. Transparency is maintained, whenever appropriate. We change header atributes if necessary for the indexing mechanism; i.e. we do not support gzip-ed encoding. We also do not support unrealistic 'expires' values that would force a cache to be flushed immediately pragma non-cache attributes are supported */ package de.anomic.http; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PushbackInputStream; import java.net.BindException; import java.net.ConnectException; import java.net.MalformedURLException; import java.net.NoRouteToHostException; import java.net.Socket; import java.net.URL; import java.net.UnknownHostException; import java.util.Date; import java.util.HashSet; import java.util.Properties; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; import java.util.zip.GZIPOutputStream; import de.anomic.htmlFilter.htmlFilterContentTransformer; import de.anomic.htmlFilter.htmlFilterOutputStream; import de.anomic.htmlFilter.htmlFilterTransformer; import de.anomic.plasma.plasmaHTCache; import de.anomic.plasma.plasmaParser; import de.anomic.plasma.plasmaSwitchboard; import de.anomic.plasma.plasmaURL; import de.anomic.server.serverCore; import de.anomic.server.serverFileUtils; import de.anomic.server.serverSwitch; import de.anomic.server.logging.serverLog; import de.anomic.server.logging.serverMiniLogFormatter; import de.anomic.yacy.yacyCore; public final class httpdProxyHandler extends httpdAbstractHandler implements httpdHandler { // static variables // can only be instantiated upon first instantiation of this class object private static plasmaSwitchboard switchboard = null; private static plasmaHTCache cacheManager = null; public static HashSet yellowList = null; private static int timeout = 30000; private static boolean yacyTrigger = true; public static boolean isTransparentProxy = false; public static boolean remoteProxyUse = false; public static String remoteProxyHost = ""; public static int remoteProxyPort = -1; public static String remoteProxyNoProxy = ""; public static String[] remoteProxyNoProxyPatterns = null; private static final HashSet remoteProxyAllowProxySet = new HashSet(); private static final HashSet remoteProxyDisallowProxySet = new HashSet(); private static htmlFilterTransformer transformer = null; public static final String userAgent = "yacy (" + httpc.systemOST +") yacy.net"; private File htRootPath = null; private static boolean doAccessLogging = false; /** * Do logging configuration for special proxy access log file */ static { // Doing logger initialisation try { serverLog.logInfo("PROXY","Configuring proxy access logging ..."); // getting the logging manager LogManager manager = LogManager.getLogManager(); String className = httpdProxyHandler.class.getName(); // determining if proxy access logging is enabled String enabled = manager.getProperty("de.anomic.http.httpdProxyHandler.logging.enabled"); if ("true".equalsIgnoreCase(enabled)) { // reading out some needed configuration properties int limit = 1024*1024, count = 20; String pattern = manager.getProperty(className + ".logging.FileHandler.pattern"); if (pattern == null) pattern = "DATA/LOG/proxyAccess%u%g.log"; String limitStr = manager.getProperty(className + ".logging.FileHandler.limit"); if (limitStr != null) try { limit = Integer.valueOf(limitStr).intValue(); } catch (NumberFormatException e) {} String countStr = manager.getProperty(className + ".logging.FileHandler.count"); if (countStr != null) try { count = Integer.valueOf(countStr).intValue(); } catch (NumberFormatException e) {} // creating the proxy access logger Logger proxyLogger = Logger.getLogger("PROXY.access"); proxyLogger.setUseParentHandlers(false); proxyLogger.setLevel(Level.FINEST); FileHandler txtLog = new FileHandler(pattern,limit,count,true); txtLog.setFormatter(new serverMiniLogFormatter()); txtLog.setLevel(Level.FINEST); proxyLogger.addHandler(txtLog); doAccessLogging = true; serverLog.logInfo("PROXY","Proxy access logging configuration done." + "\n\tFilename: " + pattern + "\n\tLimit: " + limitStr + "\n\tCount: " + countStr); } else { serverLog.logInfo("PROXY","Proxy access logging is deactivated."); } } catch (Exception e) { serverLog.logSevere("PROXY","Unable to configure proxy access logging.",e); } } /** * Special logger instance for proxy access logging much similar * to the squid access.log file */ private final serverLog proxyLog = new serverLog("PROXY.access"); /** * Reusable {@link StringBuffer} for logging */ private final StringBuffer logMessage = new StringBuffer(); /** * Reusable {@link StringBuffer} to generate the useragent string */ private final StringBuffer userAgentStr = new StringBuffer(); // class methods public httpdProxyHandler(serverSwitch sb) { // creating a logger this.theLogger = new serverLog("PROXY"); if (switchboard == null) { switchboard = (plasmaSwitchboard) sb; cacheManager = switchboard.getCacheManager(); isTransparentProxy = Boolean.valueOf(switchboard.getConfig("isTransparentProxy","false")).booleanValue(); // doing httpc init httpc.useYacyReferer = sb.getConfig("useYacyReferer", "true").equals("true"); httpc.yacyDebugMode = sb.getConfig("yacyDebugMode", "false").equals("true"); // load remote proxy data remoteProxyHost = switchboard.getConfig("remoteProxyHost",""); try { remoteProxyPort = Integer.parseInt(switchboard.getConfig("remoteProxyPort","3128")); } catch (NumberFormatException e) { remoteProxyPort = 3128; } remoteProxyUse = switchboard.getConfig("remoteProxyUse","false").equals("true"); remoteProxyNoProxy = switchboard.getConfig("remoteProxyNoProxy",""); remoteProxyNoProxyPatterns = remoteProxyNoProxy.split(","); // set timeout timeout = Integer.parseInt(switchboard.getConfig("clientTimeout", "10000")); // create a htRootPath: system pages if (htRootPath == null) { htRootPath = new File(switchboard.getRootPath(), switchboard.getConfig("htRootPath","htroot")); if (!(htRootPath.exists())) htRootPath.mkdir(); } // load a transformer transformer = new htmlFilterContentTransformer(); transformer.init(new File(switchboard.getRootPath(), switchboard.getConfig("plasmaBlueList", "")).toString()); String f; // load the yellow-list f = switchboard.getConfig("proxyYellowList", null); if (f != null) { yellowList = serverFileUtils.loadSet(f); this.theLogger.logConfig("loaded yellow-list from file " + f + ", " + yellowList.size() + " entries"); } else { yellowList = new HashSet(); } } } private static String domain(String host) { String domain = host; int pos = domain.lastIndexOf("."); if (pos >= 0) { // truncate from last part domain = domain.substring(0, pos); pos = domain.lastIndexOf("."); if (pos >= 0) { // truncate from first part domain = domain.substring(pos + 1); } } return domain; } public void handleOutgoingCookies(httpHeader requestHeader, String targethost, String clienthost) { /* The syntax for the header is: cookie = "Cookie:" cookie-version 1*((";" | ",") cookie-value) cookie-value = NAME "=" VALUE [";" path] [";" domain] cookie-version = "$Version" "=" value NAME = attr VALUE = value path = "$Path" "=" value domain = "$Domain" "=" value */ if (requestHeader.containsKey(httpHeader.COOKIE)) { Object[] entry = new Object[]{new Date(), clienthost, requestHeader.getMultiple(httpHeader.COOKIE)}; switchboard.outgoingCookies.put(targethost, entry); } } public void handleIncomingCookies(httpHeader respondHeader, String serverhost, String targetclient) { /* The syntax for the Set-Cookie response header is set-cookie = "Set-Cookie:" cookies cookies = 1#cookie cookie = NAME "=" VALUE *(";" cookie-av) NAME = attr VALUE = value cookie-av = "Comment" "=" value | "Domain" "=" value | "Max-Age" "=" value | "Path" "=" value | "Secure" | "Version" "=" 1*DIGIT */ if (respondHeader.containsKey(httpHeader.SET_COOKIE)) { Object[] entry = new Object[]{new Date(), targetclient, respondHeader.getMultiple(httpHeader.SET_COOKIE)}; switchboard.incomingCookies.put(serverhost, entry); } } /** * @param conProp a collection of properties about the connection, like URL * @param requestHeader The header lines of the connection from the request * @param respond the OutputStream to the client * @see de.anomic.http.httpdHandler#doGet(java.util.Properties, de.anomic.http.httpHeader, java.io.OutputStream) */ public void doGet(Properties conProp, httpHeader requestHeader, OutputStream respond) throws IOException { this.connectionProperties = conProp; try { // remembering the starting time of the request Date requestDate = new Date(); // remember the time... this.connectionProperties.put(httpd.CONNECTION_PROP_REQUEST_START,new Long(requestDate.getTime())); if (yacyTrigger) de.anomic.yacy.yacyCore.triggerOnlineAction(); switchboard.proxyLastAccess = System.currentTimeMillis(); // using an ByteCount OutputStream to count the send bytes (needed for the logfile) respond = new httpdByteCountOutputStream(respond,conProp.getProperty(httpd.CONNECTION_PROP_REQUESTLINE).length() + 2); String host = conProp.getProperty(httpd.CONNECTION_PROP_HOST); String path = conProp.getProperty(httpd.CONNECTION_PROP_PATH); // always starts with leading '/' String args = conProp.getProperty(httpd.CONNECTION_PROP_ARGS); // may be null if no args were given String ip = conProp.getProperty(httpd.CONNECTION_PROP_CLIENTIP); // the ip from the connecting peer int port, pos; if ((pos = host.indexOf(":")) < 0) { port = 80; } else { port = Integer.parseInt(host.substring(pos + 1)); host = host.substring(0, pos); } String ext; if ((pos = path.lastIndexOf('.')) < 0) { ext = ""; } else { ext = path.substring(pos + 1).toLowerCase(); } URL url = null; try { url = new URL("http", host, port, (args == null) ? path : path + "?" + args); } catch (MalformedURLException e) { String errorMsg = "ERROR: internal error with url generation: host=" + host + ", port=" + port + ", path=" + path + ", args=" + args; serverLog.logSevere("PROXY", errorMsg); httpd.sendRespondError(conProp,respond,4,501,null,errorMsg,e); return; } // check the blacklist // blacklist idea inspired by [AS]: // respond a 404 for all AGIS ("all you get is shit") servers String hostlow = host.toLowerCase(); if (switchboard.urlBlacklist.isListed(hostlow, path)) { httpd.sendRespondError(conProp,respond,4,403,null, "URL '" + hostlow + "' blocked by yacy proxy (blacklisted)",null); this.theLogger.logInfo("AGIS blocking of host '" + hostlow + "'"); return; } // handle outgoing cookies handleOutgoingCookies(requestHeader, host, ip); // set another userAgent, if not yellowlisted if ((yellowList != null) && (!(yellowList.contains(domain(hostlow))))) { // change the User-Agent requestHeader.put(httpHeader.USER_AGENT, generateUserAgent(requestHeader)); } // decide wether to use a cache entry or connect to the network File cacheFile = cacheManager.getCachePath(url); String urlHash = plasmaURL.urlHash(url); httpHeader cachedResponseHeader = cacheManager.getCachedResponse(urlHash); boolean cacheExists = ((cacheFile.exists()) && (cacheFile.isFile()) && (cachedResponseHeader != null)); // why are files unzipped upon arrival? why not zip all files in cache? // This follows from the following premises // (a) no file shall be unzip-ed more than once to prevent unnessesary computing time // (b) old cache entries shall be comparable with refill-entries to detect/distiguish case 3+4 // (c) the indexing mechanism needs files unzip-ed, a schedule could do that later // case b and c contradicts, if we use a scheduler, because files in a stale cache would be unzipped // and the newly arrival would be zipped and would have to be unzipped upon load. But then the // scheduler is superfluous. Therefore the only reminding case is // (d) cached files shall be either all zipped or unzipped // case d contradicts with a, because files need to be unzipped for indexing. Therefore // the only remaining case is to unzip files right upon load. Thats what we do here. // finally use existing cache if appropriate // here we must decide weather or not to save the data // to a cache // we distinguish four CACHE STATE cases: // 1. cache fill // 2. cache fresh - no refill // 3. cache stale - refill - necessary // 4. cache stale - refill - superfluous // in two of these cases we trigger a scheduler to handle newly arrived files: // case 1 and case 3 plasmaHTCache.Entry cacheEntry = (cachedResponseHeader == null) ? null : cacheManager.newEntry( requestDate, // init date 0, // crawling depth url, // url "", // name of the url is unknown requestHeader, // request headers "200 OK", // request status cachedResponseHeader, // response headers null, // initiator switchboard.defaultProxyProfile // profile ); if (cacheExists && cacheEntry.shallUseCacheForProxy()) { fulfillRequestFromCache(conProp,url,ext,requestHeader,cachedResponseHeader,cacheFile,respond); } else { fulfillRequestFromWeb(conProp,url,ext,requestHeader,cachedResponseHeader,cacheFile,respond); } } catch (Exception e) { try { String exTxt = e.getMessage(); if ((exTxt!=null)&&(exTxt.startsWith("Socket closed"))) { this.forceConnectionClose(); } else if (!conProp.containsKey(httpd.CONNECTION_PROP_PROXY_RESPOND_HEADER)) { String errorMsg = "Unexpected Error. " + e.getClass().getName() + ": " + e.getMessage(); httpd.sendRespondError(conProp,respond,4,501,null,errorMsg,e); this.theLogger.logSevere(errorMsg); } else { this.forceConnectionClose(); } } catch (Exception ee) { this.forceConnectionClose(); } } finally { try { respond.flush(); } catch (Exception e) {} if (respond instanceof httpdByteCountOutputStream) ((httpdByteCountOutputStream)respond).finish(); this.connectionProperties.put(httpd.CONNECTION_PROP_REQUEST_END,new Long(System.currentTimeMillis())); this.connectionProperties.put(httpd.CONNECTION_PROP_PROXY_RESPOND_SIZE,new Long(((httpdByteCountOutputStream)respond).getCount())); this.logProxyAccess(); } } private void fulfillRequestFromWeb(Properties conProp, URL url,String ext, httpHeader requestHeader, httpHeader cachedResponseHeader, File cacheFile, OutputStream respond) { GZIPOutputStream gzippedOut = null; httpChunkedOutputStream chunkedOut = null; OutputStream hfos = null; httpc remote = null; httpc.response res = null; try { String host = conProp.getProperty(httpd.CONNECTION_PROP_HOST); String path = conProp.getProperty(httpd.CONNECTION_PROP_PATH); // always starts with leading '/' String args = conProp.getProperty(httpd.CONNECTION_PROP_ARGS); // may be null if no args were given String ip = conProp.getProperty(httpd.CONNECTION_PROP_CLIENTIP); // the ip from the connecting peer String httpVer = conProp.getProperty(httpd.CONNECTION_PROP_HTTP_VER); // the ip from the connecting peer int port, pos; if ((pos = host.indexOf(":")) < 0) { port = 80; } else { port = Integer.parseInt(host.substring(pos + 1)); host = host.substring(0, pos); } // resolve yacy and yacyh domains String yAddress = yacyCore.seedDB.resolveYacyAddress(host); // re-calc the url path String remotePath = (args == null) ? path : (path + "?" + args); // with leading '/' // attach possible yacy-sublevel-domain if ((yAddress != null) && ((pos = yAddress.indexOf("/")) >= 0) && (!(remotePath.startsWith("/env"))) // this is the special path, staying always at root-level ) remotePath = yAddress.substring(pos) + remotePath; // open the connection remote = (yAddress == null) ? newhttpc(host, port, timeout) : newhttpc(yAddress, timeout); // removing hop by hop headers this.removeHopByHopHeaders(requestHeader); // send request res = remote.GET(remotePath, requestHeader); conProp.put(httpd.CONNECTION_PROP_CLIENT_REQUEST_HEADER,requestHeader); // request has been placed and result has been returned. work off response String[] resStatus = res.status.split(" "); // determine if it's an internal error of the httpc if (res.responseHeader.size() == 0) { throw new Exception((resStatus.length > 1) ? resStatus[1] : "Internal httpc error"); } // if the content length is not set we have to use chunked transfer encoding long contentLength = res.responseHeader.contentLength(); if (contentLength < 0) { // according to http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html // a 204,304 message must not contain a message body. // Therefore we need to set the content-length to 0. if (res.status.startsWith("204") || res.status.startsWith("304")) { res.responseHeader.put(httpHeader.CONTENT_LENGTH,"0"); } else { if (httpVer.equals("HTTP/0.9") || httpVer.equals("HTTP/1.0")) { conProp.setProperty(httpd.CONNECTION_PROP_PERSISTENT,"close"); } else { chunkedOut = new httpChunkedOutputStream(respond); } res.responseHeader.remove(httpHeader.CONTENT_LENGTH); } } // if (((String)requestHeader.get(httpHeader.ACCEPT_ENCODING,"")).indexOf("gzip") != -1) { // zipped = new GZIPOutputStream((chunked != null) ? chunked : respond); // res.responseHeader.put(httpHeader.CONTENT_ENCODING, "gzip"); // res.responseHeader.remove(httpHeader.CONTENT_LENGTH); // } // the cache does either not exist or is (supposed to be) stale long sizeBeforeDelete = -1; if ((cacheFile.exists()) && (cacheFile.isFile()) && (cachedResponseHeader != null)) { // delete the cache sizeBeforeDelete = cacheFile.length(); cacheManager.deleteFile(url); conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REFRESH_MISS"); } // reserver cache entry Date requestDate = new Date(((Long)conProp.get(httpd.CONNECTION_PROP_REQUEST_START)).longValue()); plasmaHTCache.Entry cacheEntry = cacheManager.newEntry( requestDate, 0, url, "", requestHeader, res.status, res.responseHeader, null, switchboard.defaultProxyProfile ); // handle file types and make (possibly transforming) output stream if ((!(transformer.isIdentityTransformer())) && ((ext == null) || (!(plasmaParser.mediaExtContains(ext)))) && (plasmaParser.realtimeParsableMimeTypesContains(res.responseHeader.mime()))) { // make a transformer this.theLogger.logFine("create transformer for URL " + url); hfos = new htmlFilterOutputStream((gzippedOut != null) ? gzippedOut : ((chunkedOut != null)? chunkedOut : respond), null, transformer, (ext.length() == 0)); } else { // simply pass through without parsing this.theLogger.logFine("create passthrough for URL " + url + ", extension '" + ext + "', mime-type '" + res.responseHeader.mime() + "'"); hfos = (gzippedOut != null) ? gzippedOut : ((chunkedOut != null)? chunkedOut : respond); } // handle incoming cookies handleIncomingCookies(res.responseHeader, host, ip); // remove hop by hop headers this.removeHopByHopHeaders(res.responseHeader); // sending the respond header back to the client if (chunkedOut != null) { res.responseHeader.put(httpHeader.TRANSFER_ENCODING, "chunked"); } httpd.sendRespondHeader( conProp, respond, httpVer, Integer.parseInt((resStatus.length > 0) ? resStatus[0]:"503"), (resStatus.length > 1) ? resStatus[1] : null, res.responseHeader); String storeError; if ((storeError = cacheEntry.shallStoreCacheForProxy()) == null) { // we write a new cache entry if ((contentLength > 0) && (contentLength < 1048576)) // if the length is known and < 1 MB { // ok, we don't write actually into a file, only to RAM, and schedule writing the file. byte[] cacheArray = res.writeContent(hfos); this.theLogger.logFine("writeContent of " + url + " produced cacheArray = " + ((cacheArray == null) ? "null" : ("size=" + cacheArray.length))); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); if (sizeBeforeDelete == -1) { // totally fresh file //cacheEntry.status = plasmaHTCache.CACHE_FILL; // it's an insert cacheEntry.cacheArray = cacheArray; cacheManager.push(cacheEntry); conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_MISS"); } else if (sizeBeforeDelete == cacheArray.length) { // before we came here we deleted a cache entry cacheArray = null; //cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_BAD; //cacheManager.push(cacheEntry); // unnecessary update conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REF_FAIL_HIT"); } else { // before we came here we deleted a cache entry //cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_GOOD; cacheEntry.cacheArray = cacheArray; cacheManager.push(cacheEntry); // necessary update, write response header to cache conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REFRESH_MISS"); } } else { // the file is too big to cache it in the ram, or the size is unknown // write to file right here. cacheFile.getParentFile().mkdirs(); res.writeContent(hfos, cacheFile); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); this.theLogger.logFine("for write-file of " + url + ": contentLength = " + contentLength + ", sizeBeforeDelete = " + sizeBeforeDelete); cacheManager.writeFileAnnouncement(cacheFile); if (sizeBeforeDelete == -1) { // totally fresh file //cacheEntry.status = plasmaHTCache.CACHE_FILL; // it's an insert cacheManager.push(cacheEntry); conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_MISS"); } else if (sizeBeforeDelete == cacheFile.length()) { // before we came here we deleted a cache entry //cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_BAD; //cacheManager.push(cacheEntry); // unnecessary update conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REF_FAIL_HIT"); } else { // before we came here we deleted a cache entry //cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_GOOD; cacheManager.push(cacheEntry); // necessary update, write response header to cache conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REFRESH_MISS"); } // beware! all these writings will not fill the cacheEntry.cacheArray // that means they are not available for the indexer (except they are scraped before) } } else { // no caching this.theLogger.logFine(cacheFile.toString() + " not cached: " + storeError); res.writeContent(hfos, null); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); if (sizeBeforeDelete == -1) { // no old file and no load. just data passing //cacheEntry.status = plasmaHTCache.CACHE_PASSING; //cacheManager.push(cacheEntry); } else { // before we came here we deleted a cache entry //cacheEntry.status = plasmaHTCache.CACHE_STALE_NO_RELOAD; //cacheManager.push(cacheEntry); } conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_MISS"); } if (gzippedOut != null) { gzippedOut.finish(); } if (chunkedOut != null) { chunkedOut.finish(); chunkedOut.flush(); } } catch (Exception e) { // this may happen if // - the targeted host does not exist // - anything with the remote server was wrong. // - the client unexpectedly closed the connection ... try { // deleting cached content if (cacheFile.exists()) cacheFile.delete(); // doing some errorhandling ... int httpStatusCode = 404; String httpStatusText = null; String errorMessage = null; Exception errorExc = e; + boolean unknownError = false; if (e instanceof ConnectException) { httpStatusCode = 403; httpStatusText = "Connection refused"; - errorMessage = "Connection refused by destination host"; + errorMessage = "Connection refused by destination host"; } else if (e instanceof BindException) { errorMessage = "Unable to establish a connection to the destination host"; } else if (e instanceof NoRouteToHostException) { errorMessage = "No route to destination host"; } else if (e instanceof UnknownHostException) { errorMessage = "IP address of the destination host could not be determined"; } else { - if (e.getMessage().indexOf("Corrupt GZIP trailer") >= 0) { + String exceptionMsg = e.getMessage(); + if ((exceptionMsg != null) && (exceptionMsg.indexOf("Corrupt GZIP trailer") >= 0)) { // just do nothing, we leave it this way this.theLogger.logFine("ignoring bad gzip trail for URL " + url + " (" + e.getMessage() + ")"); this.forceConnectionClose(); + } else if ((exceptionMsg != null) && (exceptionMsg.indexOf("Connection reset")>= 0)) { + errorMessage = "Connection reset"; } else if ((remote != null)&&(remote.isClosed())) { // TODO: query for broken pipe - errorMessage = "destination host unexpectedly closed connection"; + errorMessage = "Destination host unexpectedly closed connection"; } else { errorMessage = "Unexpected Error. " + e.getClass().getName() + ": " + e.getMessage(); + unknownError = true; } } // sending back an error message to the client if (!conProp.containsKey(httpd.CONNECTION_PROP_PROXY_RESPOND_HEADER)) { httpd.sendRespondError(conProp,respond,4,httpStatusCode,httpStatusText,errorMessage,errorExc); } else { - this.theLogger.logFine("Error while processing request '" + - conProp.getProperty(httpd.CONNECTION_PROP_REQUESTLINE,"unknown") + "':" + - "\n" + errorMessage,e); + if (unknownError) { + this.theLogger.logFine("Error while processing request '" + + conProp.getProperty(httpd.CONNECTION_PROP_REQUESTLINE,"unknown") + "':" + + "\n" + Thread.currentThread().getName() + + "\n" + errorMessage,e); + } else { + this.theLogger.logFine("Error while processing request '" + + conProp.getProperty(httpd.CONNECTION_PROP_REQUESTLINE,"unknown") + "':" + + "\n" + Thread.currentThread().getName() + + "\n" + errorMessage); + } this.forceConnectionClose(); } } catch (Exception ee) { this.forceConnectionClose(); } } finally { if (remote != null) httpc.returnInstance(remote); } } private void fulfillRequestFromCache( Properties conProp, URL url, String ext, httpHeader requestHeader, httpHeader cachedResponseHeader, File cacheFile, OutputStream respond ) throws IOException { String httpVer = conProp.getProperty(httpd.CONNECTION_PROP_HTTP_VER); httpChunkedOutputStream chunkedOut = null; GZIPOutputStream gzippedOut = null; OutputStream hfos = null; // we respond on the request by using the cache, the cache is fresh try { // remove hop by hop headers this.removeHopByHopHeaders(cachedResponseHeader); // replace date field in old header by actual date, this is according to RFC cachedResponseHeader.put(httpHeader.DATE, httpc.dateString(httpc.nowDate())); // if (((String)requestHeader.get(httpHeader.ACCEPT_ENCODING,"")).indexOf("gzip") != -1) { // chunked = new httpChunkedOutputStream(respond); // zipped = new GZIPOutputStream(chunked); // cachedResponseHeader.put(httpHeader.TRANSFER_ENCODING, "chunked"); // cachedResponseHeader.put(httpHeader.CONTENT_ENCODING, "gzip"); // } else { // maybe the content length is missing // if (!(cachedResponseHeader.containsKey(httpHeader.CONTENT_LENGTH))) // cachedResponseHeader.put(httpHeader.CONTENT_LENGTH, Long.toString(cacheFile.length())); // } // check if we can send a 304 instead the complete content if (requestHeader.containsKey(httpHeader.IF_MODIFIED_SINCE)) { // conditional request: freshness of cache for that condition was already // checked within shallUseCache(). Now send only a 304 response this.theLogger.logInfo("CACHE HIT/304 " + cacheFile.toString()); conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REFRESH_HIT"); // setting the content length header to 0 cachedResponseHeader.put(httpHeader.CONTENT_LENGTH, Integer.toString(0)); // send cached header with replaced date and added length httpd.sendRespondHeader(conProp,respond,httpVer,304,cachedResponseHeader); //respondHeader(respond, "304 OK", cachedResponseHeader); // respond with 'not modified' } else { // unconditional request: send content of cache this.theLogger.logInfo("CACHE HIT/203 " + cacheFile.toString()); conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_HIT"); // setting the content header to the proper length cachedResponseHeader.put(httpHeader.CONTENT_LENGTH, Long.toString(cacheFile.length())); // send cached header with replaced date and added length httpd.sendRespondHeader(conProp,respond,httpVer,203,cachedResponseHeader); //respondHeader(respond, "203 OK", cachedResponseHeader); // respond with 'non-authoritative' // make a transformer if ((!(transformer.isIdentityTransformer())) && ((ext == null) || (!(plasmaParser.mediaExtContains(ext)))) && ((cachedResponseHeader == null) || (plasmaParser.realtimeParsableMimeTypesContains(cachedResponseHeader.mime())))) { hfos = new htmlFilterOutputStream((chunkedOut != null) ? chunkedOut : respond, null, transformer, (ext.length() == 0)); } else { hfos = (gzippedOut != null) ? gzippedOut : ((chunkedOut != null)? chunkedOut : respond); } // send also the complete body now from the cache // simply read the file and transfer to out socket serverFileUtils.copy(cacheFile,hfos); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); if (gzippedOut != null) gzippedOut.finish(); if (chunkedOut != null) chunkedOut.finish(); } // that's it! } catch (Exception e) { // this happens if the client stops loading the file // we do nothing here if (conProp.containsKey(httpd.CONNECTION_PROP_PROXY_RESPOND_HEADER)) { this.theLogger.logWarning("Error while trying to send cached message body."); conProp.setProperty(httpd.CONNECTION_PROP_PERSISTENT,"close"); } else { httpd.sendRespondError(conProp,respond,4,503,"socket error: " + e.getMessage(),"socket error: " + e.getMessage(), e); } } finally { try { respond.flush(); } catch (Exception e) {} } return; } private void removeHopByHopHeaders(httpHeader headers) { /* * - Connection - Keep-Alive - Proxy-Authenticate - Proxy-Authorization - TE - Trailers - Transfer-Encoding - Upgrade */ headers.remove(httpHeader.CONNECTION); headers.remove(httpHeader.PROXY_CONNECTION); headers.remove(httpHeader.PROXY_AUTHENTICATE); headers.remove(httpHeader.PROXY_AUTHORIZATION); // special headers inserted by squid headers.remove(httpHeader.X_CACHE); headers.remove(httpHeader.X_CACHE_LOOKUP); // remove transfer encoding header headers.remove(httpHeader.TRANSFER_ENCODING); //removing yacy status headers headers.remove(httpHeader.X_YACY_KEEP_ALIVE_REQUEST_COUNT); headers.remove(httpHeader.X_YACY_ORIGINAL_REQUEST_LINE); } private void forceConnectionClose() { if (this.connectionProperties != null) { this.connectionProperties.setProperty(httpd.CONNECTION_PROP_PERSISTENT,"close"); } } public void doHead(Properties conProp, httpHeader requestHeader, OutputStream respond) throws IOException { this.connectionProperties = conProp; String method = conProp.getProperty("METHOD"); String host = conProp.getProperty("HOST"); String path = conProp.getProperty("PATH"); String args = conProp.getProperty("ARGS"); // may be null if no args were given String httpVer = conProp.getProperty(httpd.CONNECTION_PROP_HTTP_VER); switchboard.proxyLastAccess = System.currentTimeMillis(); int port; int pos; if ((pos = host.indexOf(":")) < 0) { port = 80; } else { port = Integer.parseInt(host.substring(pos + 1)); host = host.substring(0, pos); } // check the blacklist, inspired by [AS]: respond a 404 for all AGIS (all you get is shit) servers String hostlow = host.toLowerCase(); if (switchboard.urlBlacklist.isListed(hostlow, path)) { try { byte[] errorMsg = ("404 (generated): URL '" + hostlow + "' blocked by yacy proxy (blacklisted)\r\n").getBytes(); httpd.sendRespondHeader(conProp,respond,httpVer,404,"Not Found (AGIS)",0); this.theLogger.logInfo("AGIS blocking of host '" + hostlow + "'"); // debug return; } catch (Exception ee) {} } // set another userAgent, if not yellowlisted if (!(yellowList.contains(domain(hostlow)))) { // change the User-Agent requestHeader.put(httpHeader.USER_AGENT, generateUserAgent(requestHeader)); } // resolve yacy and yacyh domains String yAddress = yacyCore.seedDB.resolveYacyAddress(host); // re-calc the url path String remotePath = (args == null) ? path : (path + "?" + args); // attach possible yacy-sublevel-domain if ((yAddress != null) && ((pos = yAddress.indexOf("/")) >= 0)) remotePath = yAddress.substring(pos) + remotePath; httpc remote = null; httpc.response res = null; try { // open the connection: second is needed for [AS] patch remote = (yAddress == null) ? newhttpc(host, port, timeout): newhttpc(yAddress, timeout); // sending the http-HEAD request to the server res = remote.HEAD(remotePath, requestHeader); // removing hop by hop headers this.removeHopByHopHeaders(res.responseHeader); // sending the server respond back to the client httpd.sendRespondHeader(conProp,respond,httpVer,Integer.parseInt(res.status.split(" ")[0]),res.responseHeader); } catch (Exception e) { try { String exTxt = e.getMessage(); if ((exTxt!=null)&&(exTxt.startsWith("Socket closed"))) { this.forceConnectionClose(); } else if (!conProp.containsKey(httpd.CONNECTION_PROP_PROXY_RESPOND_HEADER)) { String errorMsg = "Unexpected Error. " + e.getClass().getName() + ": " + e.getMessage(); httpd.sendRespondError(conProp,respond,4,503,null,errorMsg,e); this.theLogger.logSevere(errorMsg); } else { this.forceConnectionClose(); } } catch (Exception ee) { this.forceConnectionClose(); } } finally { if (remote != null) httpc.returnInstance(remote); } respond.flush(); } public void doPost(Properties conProp, httpHeader requestHeader, OutputStream respond, PushbackInputStream body) throws IOException { this.connectionProperties = conProp; try { // remembering the starting time of the request Date requestDate = new Date(); // remember the time... this.connectionProperties.put(httpd.CONNECTION_PROP_REQUEST_START,new Long(requestDate.getTime())); switchboard.proxyLastAccess = System.currentTimeMillis(); // using an ByteCount OutputStream to count the send bytes respond = new httpdByteCountOutputStream(respond,conProp.getProperty(httpd.CONNECTION_PROP_REQUESTLINE).length() + 2); String host = conProp.getProperty(httpd.CONNECTION_PROP_HOST); String path = conProp.getProperty(httpd.CONNECTION_PROP_PATH); String args = conProp.getProperty(httpd.CONNECTION_PROP_ARGS); // may be null if no args were given String httpVer = conProp.getProperty(httpd.CONNECTION_PROP_HTTP_VER); int port, pos; if ((pos = host.indexOf(":")) < 0) { port = 80; } else { port = Integer.parseInt(host.substring(pos + 1)); host = host.substring(0, pos); } // set another userAgent, if not yellowlisted if (!(yellowList.contains(domain(host).toLowerCase()))) { // change the User-Agent requestHeader.put(httpHeader.USER_AGENT, generateUserAgent(requestHeader)); } // resolve yacy and yacyh domains String yAddress = yacyCore.seedDB.resolveYacyAddress(host); // re-calc the url path String remotePath = (args == null) ? path : (path + "?" + args); // attach possible yacy-sublevel-domain if ((yAddress != null) && ((pos = yAddress.indexOf("/")) >= 0)) remotePath = yAddress.substring(pos) + remotePath; httpc remote = null; httpc.response res = null; try { remote = (yAddress == null) ? newhttpc(host, port, timeout) : newhttpc(yAddress, timeout); res = remote.POST(remotePath, requestHeader, body); // filtering out unwanted headers this.removeHopByHopHeaders(res.responseHeader); // if the content length is not set we need to use chunked content encoding long contentLength = res.responseHeader.contentLength(); httpChunkedOutputStream chunked = null; if (contentLength <= 0) { res.responseHeader.put(httpHeader.TRANSFER_ENCODING, "chunked"); res.responseHeader.remove(httpHeader.CONTENT_LENGTH); chunked = new httpChunkedOutputStream(respond); } // sending response headers httpd.sendRespondHeader(conProp,respond,httpVer,Integer.parseInt(res.status.split(" ")[0]),res.responseHeader); // respondHeader(respond, res.status, res.responseHeader); res.writeContent((chunked != null) ? chunked : respond, null); if (chunked != null) chunked.finish(); remote.close(); } finally { if (remote != null) httpc.returnInstance(remote); } respond.flush(); } catch (Exception e) { try { String exTxt = e.getMessage(); if ((exTxt!=null)&&(exTxt.startsWith("Socket closed"))) { this.forceConnectionClose(); } else if (!conProp.containsKey(httpd.CONNECTION_PROP_PROXY_RESPOND_HEADER)) { String errorMsg = "Unexpected Error. " + e.getClass().getName() + ": " + e.getMessage(); httpd.sendRespondError(conProp,respond,4,503,null,errorMsg,e); this.theLogger.logSevere(errorMsg); } else { this.forceConnectionClose(); } } catch (Exception ee) { this.forceConnectionClose(); } } finally { respond.flush(); if (respond instanceof httpdByteCountOutputStream) ((httpdByteCountOutputStream)respond).finish(); this.connectionProperties.put(httpd.CONNECTION_PROP_REQUEST_END,new Long(System.currentTimeMillis())); this.connectionProperties.put(httpd.CONNECTION_PROP_PROXY_RESPOND_SIZE,new Long(((httpdByteCountOutputStream)respond).getCount())); this.logProxyAccess(); } } public void doConnect(Properties conProp, de.anomic.http.httpHeader requestHeader, InputStream clientIn, OutputStream clientOut) throws IOException { this.connectionProperties = conProp; switchboard.proxyLastAccess = System.currentTimeMillis(); String host = conProp.getProperty("HOST"); int port = Integer.parseInt(conProp.getProperty("PORT")); String httpVersion = conProp.getProperty("HTTP"); int timeout = Integer.parseInt(switchboard.getConfig("clientTimeout", "10000")); // possibly branch into PROXY-PROXY connection if (remoteProxyUse) { httpc remoteProxy = null; try { remoteProxy = httpc.getInstance(host, port, timeout, false, remoteProxyHost, remoteProxyPort); httpc.response response = remoteProxy.CONNECT(host, port, requestHeader); response.print(); if (response.success()) { // replace connection details host = remoteProxyHost; port = remoteProxyPort; // go on (see below) } else { // pass error response back to client httpd.sendRespondHeader(conProp,clientOut,httpVersion,Integer.parseInt(response.status.split(" ")[0]),response.responseHeader); //respondHeader(clientOut, response.status, response.responseHeader); return; } } catch (Exception e) { throw new IOException(e.getMessage()); } finally { if (remoteProxy != null) httpc.returnInstance(remoteProxy); } } // try to establish connection to remote host Socket sslSocket = new Socket(host, port); sslSocket.setSoTimeout(timeout); // waiting time for write sslSocket.setSoLinger(true, timeout); // waiting time for read InputStream promiscuousIn = sslSocket.getInputStream(); OutputStream promiscuousOut = sslSocket.getOutputStream(); // now then we can return a success message clientOut.write((httpVersion + " 200 Connection established" + serverCore.crlfString + "Proxy-agent: YACY" + serverCore.crlfString + serverCore.crlfString).getBytes()); this.theLogger.logInfo("SSL CONNECTION TO " + host + ":" + port + " ESTABLISHED"); // start stream passing with mediate processes try { Mediate cs = new Mediate(sslSocket, clientIn, promiscuousOut); Mediate sc = new Mediate(sslSocket, promiscuousIn, clientOut); cs.start(); sc.start(); while ((sslSocket != null) && (sslSocket.isBound()) && (!(sslSocket.isClosed())) && (sslSocket.isConnected()) && ((cs.isAlive()) || (sc.isAlive()))) { // idle try {Thread.currentThread().sleep(1000);} catch (InterruptedException e) {} // wait a while } // set stop mode cs.pleaseTerminate(); sc.pleaseTerminate(); // wake up thread cs.interrupt(); sc.interrupt(); // ...hope they have terminated... } catch (IOException e) { //System.out.println("promiscuous termination: " + e.getMessage()); } } public class Mediate extends Thread { boolean terminate; Socket socket; InputStream in; OutputStream out; public Mediate(Socket socket, InputStream in, OutputStream out) throws IOException { this.terminate = false; this.in = in; this.out = out; this.socket = socket; } public void run() { byte[] buffer = new byte[512]; int len; try { while ((socket != null) && (socket.isBound()) && (!(socket.isClosed())) && (socket.isConnected()) && (!(terminate)) && (in != null) && (out != null) && ((len = in.read(buffer)) >= 0) ) { out.write(buffer, 0, len); } } catch (IOException e) {} } public void pleaseTerminate() { terminate = true; } } private httpc newhttpc(String server, int port, int timeout) throws IOException { // a new httpc connection, combined with possible remote proxy boolean useProxy = remoteProxyUse; // check no-proxy rule if ((useProxy) && (!(remoteProxyAllowProxySet.contains(server)))) { if (remoteProxyDisallowProxySet.contains(server)) { useProxy = false; } else { // analyse remoteProxyNoProxy; // set either remoteProxyAllowProxySet or remoteProxyDisallowProxySet accordingly int i = 0; while (i < remoteProxyNoProxyPatterns.length) { if (server.matches(remoteProxyNoProxyPatterns[i])) { // disallow proxy for this server remoteProxyDisallowProxySet.add(server); useProxy = false; break; } i++; } if (i == remoteProxyNoProxyPatterns.length) { // no pattern matches: allow server remoteProxyAllowProxySet.add(server); } } } // branch to server/proxy if (useProxy) { return httpc.getInstance(server, port, timeout, false, remoteProxyHost, remoteProxyPort); } else { return httpc.getInstance(server, port, timeout, false); } } private httpc newhttpc(String address, int timeout) throws IOException { // a new httpc connection for <host>:<port>/<path> syntax // this is called when a '.yacy'-domain is used int p = address.indexOf(":"); if (p < 0) return null; String server = address.substring(0, p); address = address.substring(p + 1); // remove possible path elements (may occur for 'virtual' subdomains p = address.indexOf("/"); if (p >= 0) address = address.substring(0, p); // cut it off int port = Integer.parseInt(address); // normal creation of httpc object return newhttpc(server, port, timeout); } private void textMessage(OutputStream out, String body) throws IOException { out.write(("HTTP/1.1 200 OK\r\n").getBytes()); out.write((httpHeader.SERVER + ": AnomicHTTPD (www.anomic.de)\r\n").getBytes()); out.write((httpHeader.DATE + ": " + httpc.dateString(httpc.nowDate()) + "\r\n").getBytes()); out.write((httpHeader.CONTENT_TYPE + ": text/plain\r\n").getBytes()); out.write((httpHeader.CONTENT_LENGTH + ": " + body.length() +"\r\n").getBytes()); out.write(("\r\n").getBytes()); out.flush(); out.write(body.getBytes()); out.flush(); } private String generateUserAgent(httpHeader requestHeaders) { this.userAgentStr.setLength(0); String browserUserAgent = (String) requestHeaders.get(httpHeader.USER_AGENT, userAgent); int pos = browserUserAgent.lastIndexOf(')'); if (pos >= 0) { this.userAgentStr .append(browserUserAgent.substring(0,pos)) .append("; YaCy ") .append(switchboard.getConfig("vString","0.1")) .append("; yacy.net") .append(browserUserAgent.substring(pos)); } else { this.userAgentStr.append(browserUserAgent); } return this.userAgentStr.toString(); } /** * This function is used to generate a logging message according to the * <a href="http://www.squid-cache.org/Doc/FAQ/FAQ-6.html">squid logging format</a>.<p> * e.g.<br> * <code>1117528623.857 178 192.168.1.201 TCP_MISS/200 1069 GET http://www.yacy.de/ - DIRECT/81.169.145.74 text/html</code> */ private final void logProxyAccess() { if (!doAccessLogging) return; this.logMessage.setLength(0); // Timestamp String currentTimestamp = Long.toString(System.currentTimeMillis()); int offset = currentTimestamp.length()-3; this.logMessage.append(currentTimestamp.substring(0,offset)); this.logMessage.append('.'); this.logMessage.append(currentTimestamp.substring(offset)); this.logMessage.append(' '); // Elapsed time Long requestStart = (Long) this.connectionProperties.get(httpd.CONNECTION_PROP_REQUEST_START); Long requestEnd = (Long) this.connectionProperties.get(httpd.CONNECTION_PROP_REQUEST_END); String elapsed = Long.toString(requestEnd.longValue()-requestStart.longValue()); for (int i=0; i<6-elapsed.length(); i++) this.logMessage.append(' '); this.logMessage.append(elapsed); this.logMessage.append(' '); // Remote Host String clientIP = this.connectionProperties.getProperty(httpd.CONNECTION_PROP_CLIENTIP); this.logMessage.append(clientIP); this.logMessage.append(' '); // Code/Status String respondStatus = this.connectionProperties.getProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_STATUS); String respondCode = this.connectionProperties.getProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"UNKNOWN"); this.logMessage.append(respondCode); this.logMessage.append("/"); this.logMessage.append(respondStatus); this.logMessage.append(' '); // Bytes Long bytes = (Long) this.connectionProperties.get(httpd.CONNECTION_PROP_PROXY_RESPOND_SIZE); this.logMessage.append(bytes.toString()); this.logMessage.append(' '); // Method String requestMethod = this.connectionProperties.getProperty(httpd.CONNECTION_PROP_METHOD); this.logMessage.append(requestMethod); this.logMessage.append(' '); // URL String requestURL = this.connectionProperties.getProperty(httpd.CONNECTION_PROP_URL); String requestArgs = this.connectionProperties.getProperty(httpd.CONNECTION_PROP_ARGS); this.logMessage.append(requestURL); if (requestArgs != null) { this.logMessage.append("?") .append(requestArgs); } this.logMessage.append(' '); // Rfc931 this.logMessage.append("-"); this.logMessage.append(' '); // Peerstatus/Peerhost String host = this.connectionProperties.getProperty(httpd.CONNECTION_PROP_HOST); this.logMessage.append("DIRECT/"); this.logMessage.append(host); this.logMessage.append(' '); // Type String mime = "-"; if (this.connectionProperties.containsKey(httpd.CONNECTION_PROP_PROXY_RESPOND_HEADER)) { httpHeader proxyRespondHeader = (httpHeader) this.connectionProperties.get(httpd.CONNECTION_PROP_PROXY_RESPOND_HEADER); mime = proxyRespondHeader.mime(); if (mime.indexOf(";") != -1) { mime = mime.substring(0,mime.indexOf(";")); } } this.logMessage.append(mime); // sending the logging message to the logger this.proxyLog.logFine(this.logMessage.toString()); } } /* proxy test: http://www.chipchapin.com/WebTools/cookietest.php? http://xlists.aza.org/moderator/cookietest/cookietest1.php http://vancouver-webpages.com/proxy/cache-test.html */
false
true
private void fulfillRequestFromWeb(Properties conProp, URL url,String ext, httpHeader requestHeader, httpHeader cachedResponseHeader, File cacheFile, OutputStream respond) { GZIPOutputStream gzippedOut = null; httpChunkedOutputStream chunkedOut = null; OutputStream hfos = null; httpc remote = null; httpc.response res = null; try { String host = conProp.getProperty(httpd.CONNECTION_PROP_HOST); String path = conProp.getProperty(httpd.CONNECTION_PROP_PATH); // always starts with leading '/' String args = conProp.getProperty(httpd.CONNECTION_PROP_ARGS); // may be null if no args were given String ip = conProp.getProperty(httpd.CONNECTION_PROP_CLIENTIP); // the ip from the connecting peer String httpVer = conProp.getProperty(httpd.CONNECTION_PROP_HTTP_VER); // the ip from the connecting peer int port, pos; if ((pos = host.indexOf(":")) < 0) { port = 80; } else { port = Integer.parseInt(host.substring(pos + 1)); host = host.substring(0, pos); } // resolve yacy and yacyh domains String yAddress = yacyCore.seedDB.resolveYacyAddress(host); // re-calc the url path String remotePath = (args == null) ? path : (path + "?" + args); // with leading '/' // attach possible yacy-sublevel-domain if ((yAddress != null) && ((pos = yAddress.indexOf("/")) >= 0) && (!(remotePath.startsWith("/env"))) // this is the special path, staying always at root-level ) remotePath = yAddress.substring(pos) + remotePath; // open the connection remote = (yAddress == null) ? newhttpc(host, port, timeout) : newhttpc(yAddress, timeout); // removing hop by hop headers this.removeHopByHopHeaders(requestHeader); // send request res = remote.GET(remotePath, requestHeader); conProp.put(httpd.CONNECTION_PROP_CLIENT_REQUEST_HEADER,requestHeader); // request has been placed and result has been returned. work off response String[] resStatus = res.status.split(" "); // determine if it's an internal error of the httpc if (res.responseHeader.size() == 0) { throw new Exception((resStatus.length > 1) ? resStatus[1] : "Internal httpc error"); } // if the content length is not set we have to use chunked transfer encoding long contentLength = res.responseHeader.contentLength(); if (contentLength < 0) { // according to http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html // a 204,304 message must not contain a message body. // Therefore we need to set the content-length to 0. if (res.status.startsWith("204") || res.status.startsWith("304")) { res.responseHeader.put(httpHeader.CONTENT_LENGTH,"0"); } else { if (httpVer.equals("HTTP/0.9") || httpVer.equals("HTTP/1.0")) { conProp.setProperty(httpd.CONNECTION_PROP_PERSISTENT,"close"); } else { chunkedOut = new httpChunkedOutputStream(respond); } res.responseHeader.remove(httpHeader.CONTENT_LENGTH); } } // if (((String)requestHeader.get(httpHeader.ACCEPT_ENCODING,"")).indexOf("gzip") != -1) { // zipped = new GZIPOutputStream((chunked != null) ? chunked : respond); // res.responseHeader.put(httpHeader.CONTENT_ENCODING, "gzip"); // res.responseHeader.remove(httpHeader.CONTENT_LENGTH); // } // the cache does either not exist or is (supposed to be) stale long sizeBeforeDelete = -1; if ((cacheFile.exists()) && (cacheFile.isFile()) && (cachedResponseHeader != null)) { // delete the cache sizeBeforeDelete = cacheFile.length(); cacheManager.deleteFile(url); conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REFRESH_MISS"); } // reserver cache entry Date requestDate = new Date(((Long)conProp.get(httpd.CONNECTION_PROP_REQUEST_START)).longValue()); plasmaHTCache.Entry cacheEntry = cacheManager.newEntry( requestDate, 0, url, "", requestHeader, res.status, res.responseHeader, null, switchboard.defaultProxyProfile ); // handle file types and make (possibly transforming) output stream if ((!(transformer.isIdentityTransformer())) && ((ext == null) || (!(plasmaParser.mediaExtContains(ext)))) && (plasmaParser.realtimeParsableMimeTypesContains(res.responseHeader.mime()))) { // make a transformer this.theLogger.logFine("create transformer for URL " + url); hfos = new htmlFilterOutputStream((gzippedOut != null) ? gzippedOut : ((chunkedOut != null)? chunkedOut : respond), null, transformer, (ext.length() == 0)); } else { // simply pass through without parsing this.theLogger.logFine("create passthrough for URL " + url + ", extension '" + ext + "', mime-type '" + res.responseHeader.mime() + "'"); hfos = (gzippedOut != null) ? gzippedOut : ((chunkedOut != null)? chunkedOut : respond); } // handle incoming cookies handleIncomingCookies(res.responseHeader, host, ip); // remove hop by hop headers this.removeHopByHopHeaders(res.responseHeader); // sending the respond header back to the client if (chunkedOut != null) { res.responseHeader.put(httpHeader.TRANSFER_ENCODING, "chunked"); } httpd.sendRespondHeader( conProp, respond, httpVer, Integer.parseInt((resStatus.length > 0) ? resStatus[0]:"503"), (resStatus.length > 1) ? resStatus[1] : null, res.responseHeader); String storeError; if ((storeError = cacheEntry.shallStoreCacheForProxy()) == null) { // we write a new cache entry if ((contentLength > 0) && (contentLength < 1048576)) // if the length is known and < 1 MB { // ok, we don't write actually into a file, only to RAM, and schedule writing the file. byte[] cacheArray = res.writeContent(hfos); this.theLogger.logFine("writeContent of " + url + " produced cacheArray = " + ((cacheArray == null) ? "null" : ("size=" + cacheArray.length))); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); if (sizeBeforeDelete == -1) { // totally fresh file //cacheEntry.status = plasmaHTCache.CACHE_FILL; // it's an insert cacheEntry.cacheArray = cacheArray; cacheManager.push(cacheEntry); conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_MISS"); } else if (sizeBeforeDelete == cacheArray.length) { // before we came here we deleted a cache entry cacheArray = null; //cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_BAD; //cacheManager.push(cacheEntry); // unnecessary update conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REF_FAIL_HIT"); } else { // before we came here we deleted a cache entry //cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_GOOD; cacheEntry.cacheArray = cacheArray; cacheManager.push(cacheEntry); // necessary update, write response header to cache conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REFRESH_MISS"); } } else { // the file is too big to cache it in the ram, or the size is unknown // write to file right here. cacheFile.getParentFile().mkdirs(); res.writeContent(hfos, cacheFile); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); this.theLogger.logFine("for write-file of " + url + ": contentLength = " + contentLength + ", sizeBeforeDelete = " + sizeBeforeDelete); cacheManager.writeFileAnnouncement(cacheFile); if (sizeBeforeDelete == -1) { // totally fresh file //cacheEntry.status = plasmaHTCache.CACHE_FILL; // it's an insert cacheManager.push(cacheEntry); conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_MISS"); } else if (sizeBeforeDelete == cacheFile.length()) { // before we came here we deleted a cache entry //cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_BAD; //cacheManager.push(cacheEntry); // unnecessary update conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REF_FAIL_HIT"); } else { // before we came here we deleted a cache entry //cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_GOOD; cacheManager.push(cacheEntry); // necessary update, write response header to cache conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REFRESH_MISS"); } // beware! all these writings will not fill the cacheEntry.cacheArray // that means they are not available for the indexer (except they are scraped before) } } else { // no caching this.theLogger.logFine(cacheFile.toString() + " not cached: " + storeError); res.writeContent(hfos, null); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); if (sizeBeforeDelete == -1) { // no old file and no load. just data passing //cacheEntry.status = plasmaHTCache.CACHE_PASSING; //cacheManager.push(cacheEntry); } else { // before we came here we deleted a cache entry //cacheEntry.status = plasmaHTCache.CACHE_STALE_NO_RELOAD; //cacheManager.push(cacheEntry); } conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_MISS"); } if (gzippedOut != null) { gzippedOut.finish(); } if (chunkedOut != null) { chunkedOut.finish(); chunkedOut.flush(); } } catch (Exception e) { // this may happen if // - the targeted host does not exist // - anything with the remote server was wrong. // - the client unexpectedly closed the connection ... try { // deleting cached content if (cacheFile.exists()) cacheFile.delete(); // doing some errorhandling ... int httpStatusCode = 404; String httpStatusText = null; String errorMessage = null; Exception errorExc = e; if (e instanceof ConnectException) { httpStatusCode = 403; httpStatusText = "Connection refused"; errorMessage = "Connection refused by destination host"; } else if (e instanceof BindException) { errorMessage = "Unable to establish a connection to the destination host"; } else if (e instanceof NoRouteToHostException) { errorMessage = "No route to destination host"; } else if (e instanceof UnknownHostException) { errorMessage = "IP address of the destination host could not be determined"; } else { if (e.getMessage().indexOf("Corrupt GZIP trailer") >= 0) { // just do nothing, we leave it this way this.theLogger.logFine("ignoring bad gzip trail for URL " + url + " (" + e.getMessage() + ")"); this.forceConnectionClose(); } else if ((remote != null)&&(remote.isClosed())) { // TODO: query for broken pipe errorMessage = "destination host unexpectedly closed connection"; } else { errorMessage = "Unexpected Error. " + e.getClass().getName() + ": " + e.getMessage(); } } // sending back an error message to the client if (!conProp.containsKey(httpd.CONNECTION_PROP_PROXY_RESPOND_HEADER)) { httpd.sendRespondError(conProp,respond,4,httpStatusCode,httpStatusText,errorMessage,errorExc); } else { this.theLogger.logFine("Error while processing request '" + conProp.getProperty(httpd.CONNECTION_PROP_REQUESTLINE,"unknown") + "':" + "\n" + errorMessage,e); this.forceConnectionClose(); } } catch (Exception ee) { this.forceConnectionClose(); } } finally { if (remote != null) httpc.returnInstance(remote); } }
private void fulfillRequestFromWeb(Properties conProp, URL url,String ext, httpHeader requestHeader, httpHeader cachedResponseHeader, File cacheFile, OutputStream respond) { GZIPOutputStream gzippedOut = null; httpChunkedOutputStream chunkedOut = null; OutputStream hfos = null; httpc remote = null; httpc.response res = null; try { String host = conProp.getProperty(httpd.CONNECTION_PROP_HOST); String path = conProp.getProperty(httpd.CONNECTION_PROP_PATH); // always starts with leading '/' String args = conProp.getProperty(httpd.CONNECTION_PROP_ARGS); // may be null if no args were given String ip = conProp.getProperty(httpd.CONNECTION_PROP_CLIENTIP); // the ip from the connecting peer String httpVer = conProp.getProperty(httpd.CONNECTION_PROP_HTTP_VER); // the ip from the connecting peer int port, pos; if ((pos = host.indexOf(":")) < 0) { port = 80; } else { port = Integer.parseInt(host.substring(pos + 1)); host = host.substring(0, pos); } // resolve yacy and yacyh domains String yAddress = yacyCore.seedDB.resolveYacyAddress(host); // re-calc the url path String remotePath = (args == null) ? path : (path + "?" + args); // with leading '/' // attach possible yacy-sublevel-domain if ((yAddress != null) && ((pos = yAddress.indexOf("/")) >= 0) && (!(remotePath.startsWith("/env"))) // this is the special path, staying always at root-level ) remotePath = yAddress.substring(pos) + remotePath; // open the connection remote = (yAddress == null) ? newhttpc(host, port, timeout) : newhttpc(yAddress, timeout); // removing hop by hop headers this.removeHopByHopHeaders(requestHeader); // send request res = remote.GET(remotePath, requestHeader); conProp.put(httpd.CONNECTION_PROP_CLIENT_REQUEST_HEADER,requestHeader); // request has been placed and result has been returned. work off response String[] resStatus = res.status.split(" "); // determine if it's an internal error of the httpc if (res.responseHeader.size() == 0) { throw new Exception((resStatus.length > 1) ? resStatus[1] : "Internal httpc error"); } // if the content length is not set we have to use chunked transfer encoding long contentLength = res.responseHeader.contentLength(); if (contentLength < 0) { // according to http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html // a 204,304 message must not contain a message body. // Therefore we need to set the content-length to 0. if (res.status.startsWith("204") || res.status.startsWith("304")) { res.responseHeader.put(httpHeader.CONTENT_LENGTH,"0"); } else { if (httpVer.equals("HTTP/0.9") || httpVer.equals("HTTP/1.0")) { conProp.setProperty(httpd.CONNECTION_PROP_PERSISTENT,"close"); } else { chunkedOut = new httpChunkedOutputStream(respond); } res.responseHeader.remove(httpHeader.CONTENT_LENGTH); } } // if (((String)requestHeader.get(httpHeader.ACCEPT_ENCODING,"")).indexOf("gzip") != -1) { // zipped = new GZIPOutputStream((chunked != null) ? chunked : respond); // res.responseHeader.put(httpHeader.CONTENT_ENCODING, "gzip"); // res.responseHeader.remove(httpHeader.CONTENT_LENGTH); // } // the cache does either not exist or is (supposed to be) stale long sizeBeforeDelete = -1; if ((cacheFile.exists()) && (cacheFile.isFile()) && (cachedResponseHeader != null)) { // delete the cache sizeBeforeDelete = cacheFile.length(); cacheManager.deleteFile(url); conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REFRESH_MISS"); } // reserver cache entry Date requestDate = new Date(((Long)conProp.get(httpd.CONNECTION_PROP_REQUEST_START)).longValue()); plasmaHTCache.Entry cacheEntry = cacheManager.newEntry( requestDate, 0, url, "", requestHeader, res.status, res.responseHeader, null, switchboard.defaultProxyProfile ); // handle file types and make (possibly transforming) output stream if ((!(transformer.isIdentityTransformer())) && ((ext == null) || (!(plasmaParser.mediaExtContains(ext)))) && (plasmaParser.realtimeParsableMimeTypesContains(res.responseHeader.mime()))) { // make a transformer this.theLogger.logFine("create transformer for URL " + url); hfos = new htmlFilterOutputStream((gzippedOut != null) ? gzippedOut : ((chunkedOut != null)? chunkedOut : respond), null, transformer, (ext.length() == 0)); } else { // simply pass through without parsing this.theLogger.logFine("create passthrough for URL " + url + ", extension '" + ext + "', mime-type '" + res.responseHeader.mime() + "'"); hfos = (gzippedOut != null) ? gzippedOut : ((chunkedOut != null)? chunkedOut : respond); } // handle incoming cookies handleIncomingCookies(res.responseHeader, host, ip); // remove hop by hop headers this.removeHopByHopHeaders(res.responseHeader); // sending the respond header back to the client if (chunkedOut != null) { res.responseHeader.put(httpHeader.TRANSFER_ENCODING, "chunked"); } httpd.sendRespondHeader( conProp, respond, httpVer, Integer.parseInt((resStatus.length > 0) ? resStatus[0]:"503"), (resStatus.length > 1) ? resStatus[1] : null, res.responseHeader); String storeError; if ((storeError = cacheEntry.shallStoreCacheForProxy()) == null) { // we write a new cache entry if ((contentLength > 0) && (contentLength < 1048576)) // if the length is known and < 1 MB { // ok, we don't write actually into a file, only to RAM, and schedule writing the file. byte[] cacheArray = res.writeContent(hfos); this.theLogger.logFine("writeContent of " + url + " produced cacheArray = " + ((cacheArray == null) ? "null" : ("size=" + cacheArray.length))); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); if (sizeBeforeDelete == -1) { // totally fresh file //cacheEntry.status = plasmaHTCache.CACHE_FILL; // it's an insert cacheEntry.cacheArray = cacheArray; cacheManager.push(cacheEntry); conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_MISS"); } else if (sizeBeforeDelete == cacheArray.length) { // before we came here we deleted a cache entry cacheArray = null; //cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_BAD; //cacheManager.push(cacheEntry); // unnecessary update conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REF_FAIL_HIT"); } else { // before we came here we deleted a cache entry //cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_GOOD; cacheEntry.cacheArray = cacheArray; cacheManager.push(cacheEntry); // necessary update, write response header to cache conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REFRESH_MISS"); } } else { // the file is too big to cache it in the ram, or the size is unknown // write to file right here. cacheFile.getParentFile().mkdirs(); res.writeContent(hfos, cacheFile); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); this.theLogger.logFine("for write-file of " + url + ": contentLength = " + contentLength + ", sizeBeforeDelete = " + sizeBeforeDelete); cacheManager.writeFileAnnouncement(cacheFile); if (sizeBeforeDelete == -1) { // totally fresh file //cacheEntry.status = plasmaHTCache.CACHE_FILL; // it's an insert cacheManager.push(cacheEntry); conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_MISS"); } else if (sizeBeforeDelete == cacheFile.length()) { // before we came here we deleted a cache entry //cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_BAD; //cacheManager.push(cacheEntry); // unnecessary update conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REF_FAIL_HIT"); } else { // before we came here we deleted a cache entry //cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_GOOD; cacheManager.push(cacheEntry); // necessary update, write response header to cache conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_REFRESH_MISS"); } // beware! all these writings will not fill the cacheEntry.cacheArray // that means they are not available for the indexer (except they are scraped before) } } else { // no caching this.theLogger.logFine(cacheFile.toString() + " not cached: " + storeError); res.writeContent(hfos, null); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); if (sizeBeforeDelete == -1) { // no old file and no load. just data passing //cacheEntry.status = plasmaHTCache.CACHE_PASSING; //cacheManager.push(cacheEntry); } else { // before we came here we deleted a cache entry //cacheEntry.status = plasmaHTCache.CACHE_STALE_NO_RELOAD; //cacheManager.push(cacheEntry); } conProp.setProperty(httpd.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_MISS"); } if (gzippedOut != null) { gzippedOut.finish(); } if (chunkedOut != null) { chunkedOut.finish(); chunkedOut.flush(); } } catch (Exception e) { // this may happen if // - the targeted host does not exist // - anything with the remote server was wrong. // - the client unexpectedly closed the connection ... try { // deleting cached content if (cacheFile.exists()) cacheFile.delete(); // doing some errorhandling ... int httpStatusCode = 404; String httpStatusText = null; String errorMessage = null; Exception errorExc = e; boolean unknownError = false; if (e instanceof ConnectException) { httpStatusCode = 403; httpStatusText = "Connection refused"; errorMessage = "Connection refused by destination host"; } else if (e instanceof BindException) { errorMessage = "Unable to establish a connection to the destination host"; } else if (e instanceof NoRouteToHostException) { errorMessage = "No route to destination host"; } else if (e instanceof UnknownHostException) { errorMessage = "IP address of the destination host could not be determined"; } else { String exceptionMsg = e.getMessage(); if ((exceptionMsg != null) && (exceptionMsg.indexOf("Corrupt GZIP trailer") >= 0)) { // just do nothing, we leave it this way this.theLogger.logFine("ignoring bad gzip trail for URL " + url + " (" + e.getMessage() + ")"); this.forceConnectionClose(); } else if ((exceptionMsg != null) && (exceptionMsg.indexOf("Connection reset")>= 0)) { errorMessage = "Connection reset"; } else if ((remote != null)&&(remote.isClosed())) { // TODO: query for broken pipe errorMessage = "Destination host unexpectedly closed connection"; } else { errorMessage = "Unexpected Error. " + e.getClass().getName() + ": " + e.getMessage(); unknownError = true; } } // sending back an error message to the client if (!conProp.containsKey(httpd.CONNECTION_PROP_PROXY_RESPOND_HEADER)) { httpd.sendRespondError(conProp,respond,4,httpStatusCode,httpStatusText,errorMessage,errorExc); } else { if (unknownError) { this.theLogger.logFine("Error while processing request '" + conProp.getProperty(httpd.CONNECTION_PROP_REQUESTLINE,"unknown") + "':" + "\n" + Thread.currentThread().getName() + "\n" + errorMessage,e); } else { this.theLogger.logFine("Error while processing request '" + conProp.getProperty(httpd.CONNECTION_PROP_REQUESTLINE,"unknown") + "':" + "\n" + Thread.currentThread().getName() + "\n" + errorMessage); } this.forceConnectionClose(); } } catch (Exception ee) { this.forceConnectionClose(); } } finally { if (remote != null) httpc.returnInstance(remote); } }
diff --git a/src/main/java/net/frontlinesms/ui/i18n/InternationalisationUtils.java b/src/main/java/net/frontlinesms/ui/i18n/InternationalisationUtils.java index 706b8f7..5bf1bed 100644 --- a/src/main/java/net/frontlinesms/ui/i18n/InternationalisationUtils.java +++ b/src/main/java/net/frontlinesms/ui/i18n/InternationalisationUtils.java @@ -1,411 +1,413 @@ /* * FrontlineSMS <http://www.frontlinesms.com> * Copyright 2007, 2008 kiwanja * * This file is part of FrontlineSMS. * * FrontlineSMS is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * FrontlineSMS is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with FrontlineSMS. If not, see <http://www.gnu.org/licenses/>. */ package net.frontlinesms.ui.i18n; import static net.frontlinesms.FrontlineSMSConstants.COMMON_FAILED; import static net.frontlinesms.FrontlineSMSConstants.COMMON_OUTBOX; import static net.frontlinesms.FrontlineSMSConstants.COMMON_PENDING; import static net.frontlinesms.FrontlineSMSConstants.COMMON_RETRYING; import static net.frontlinesms.FrontlineSMSConstants.COMMON_SENT; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Currency; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.MissingResourceException; import net.frontlinesms.FrontlineSMSConstants; import net.frontlinesms.FrontlineUtils; import net.frontlinesms.data.domain.Email; import net.frontlinesms.resources.ResourceUtils; import net.frontlinesms.ui.FrontlineUI; import org.apache.log4j.Logger; import thinlet.Thinlet; /** * Utilities for helping internationalise text etc. * @author Alex * * TODO always use UTF-8 with no exceptions. All Unicode characters, and therefore all characters, can be encoded as UTF-8 */ public class InternationalisationUtils { //> STATIC PROPERTIES /** Name of the directory containing the languages files. This is located within the config directory. */ private static final String LANGUAGES_DIRECTORY_NAME = "languages"; /** The filename of the default language bundle. */ public static final String DEFAULT_LANGUAGE_BUNDLE_FILENAME = "frontlineSMS.properties"; /** The path to the default language bundle on the classpath. */ public static final String DEFAULT_LANGUAGE_BUNDLE_PATH = "/resources/languages/" + DEFAULT_LANGUAGE_BUNDLE_FILENAME; /** Logging object for this class */ private static Logger LOG = FrontlineUtils.getLogger(InternationalisationUtils.class); //> GENERAL i18n HELP METHODS /** The default characterset, UTF-8. This must be available for every JVM. */ public static final Charset CHARSET_UTF8 = Charset.forName("UTF-8"); //> /** * Return an internationalised message for this key. * <br> This method tries to get the string for the current bundle and if it does not exist, it looks into * the default bundle (English GB). * @param key * @return the internationalised text, or the english text if no internationalised text could be found */ public static String getI18NString(String key) { if(FrontlineUI.currentResourceBundle != null) { try { return FrontlineUI.currentResourceBundle.getValue(key); } catch(MissingResourceException ex) {} } return Thinlet.DEFAULT_ENGLISH_BUNDLE.get(key); } /** * Return the list of internationalised message for this prefix. * <br> This method tries to get the strings from the current bundle, and if it does not exist, it looks into * the default bundle * @param key * @return the list internationalised text, or an empty list if no internationalised text could be found */ public static List<String> getI18nStrings(String key) { if(FrontlineUI.currentResourceBundle != null) { try { return FrontlineUI.currentResourceBundle.getValues(key); } catch(MissingResourceException ex) {} } return LanguageBundle.getValues(Thinlet.DEFAULT_ENGLISH_BUNDLE, key); } /** * Return an internationalised message for this key. This calls {@link #getI18NString(String)} * and then replaces any instance of {@link FrontlineSMSConstants#ARG_VALUE} with @param argValues * * @param key * @param argValues * @return an internationalised string with any substitution variables converted */ public static String getI18NString(String key, String... argValues) { String string = getI18NString(key); if(argValues != null) { // Iterate backwards through the replacements and replace the arguments with the new values. Need // to iterate backwards so e.g. %10 is replaced before %1 for (int i = argValues.length-1; i >= 0; --i) { String arg = argValues[i]; if(arg != null) { if(LOG.isDebugEnabled()) LOG.debug("Subbing " + arg + " as " + (FrontlineSMSConstants.ARG_VALUE + i) + " into: " + string); string = string.replace(FrontlineSMSConstants.ARG_VALUE + i, arg); } } } return string; } /** * Return an internationalised message for this key. This converts the integer to a {@link String} and then * calls {@link #getI18NString(String, String...)} with this argument. * @param key * @param intValue * @return the internationalised string with the supplied integer embedded at the appropriate place */ public static String getI18NString(String key, int intValue) { return getI18NString(key, Integer.toString(intValue)); } /** * Parses a string representation of an amount of currency to an integer. This will handle * cases where the currency symbol has not been included in the <code>currencyString</code> * @param currencyString * @return the currency amount represented by the supplied string * @throws ParseException */ public static final double parseCurrency(String currencyString) throws ParseException { NumberFormat currencyFormat = InternationalisationUtils.getCurrencyFormat(); String currencySymbol = InternationalisationUtils.getCurrencySymbol(); if(!currencyString.contains(currencySymbol)) { if(InternationalisationUtils.isCurrencySymbolPrefix()) currencyString = currencySymbol + currencyString; else if(InternationalisationUtils.isCurrencySymbolSuffix()) currencyString += currencySymbol; /* else allow the parse exception to be thrown! */ } return currencyFormat.parse(currencyString).doubleValue(); } /** * Checks if the currency currency symbol is a suffix to the formatted currency value string. * @return <code>true</code> if the currency symbol should be placed after the value; <code>false</code> otherwise. */ public static boolean isCurrencySymbolSuffix() { String testString = InternationalisationUtils.formatCurrency(12.34); String currencySymbol = InternationalisationUtils.getCurrencySymbol(); int symbolPosition = testString.indexOf(currencySymbol); return symbolPosition == testString.length()-currencySymbol.length(); } /** * Checks if the currency currency symbol is a prefix to the formatted currency value string. * @return <code>true</code> if the currency symbol should be placed before the currency value; <code>false</code> otherwise. */ public static boolean isCurrencySymbolPrefix() { String testString = InternationalisationUtils.formatCurrency(12.34); int symbolPosition = testString.indexOf(InternationalisationUtils.getCurrencySymbol()); return symbolPosition == 0; } /** * @param value * @return a formatted currency string * @see #formatCurrency(double, boolean) */ public static final String formatCurrency(double value) { return InternationalisationUtils.formatCurrency(value, true); } /** * Format an integer into a decimal string for use as a currency value. * @param value * @param showSymbol * @return a formatted currency string */ public static final String formatCurrency(double value, boolean showSymbol) { String formatted = InternationalisationUtils.getCurrencyFormat().format(value); if(!showSymbol) { formatted = formatted.replace(InternationalisationUtils.getCurrencySymbol(), ""); } return formatted; } /** @return decimal separator to be used with the currect currency */ public static final char getDecimalSeparator() { return ((DecimalFormat)InternationalisationUtils.getCurrencyFormat()).getDecimalFormatSymbols().getDecimalSeparator(); } /** @return symbol used to represent the current currency */ public static final String getCurrencySymbol() { return ((DecimalFormat)InternationalisationUtils.getCurrencyFormat()).getDecimalFormatSymbols().getCurrencySymbol(); } /** @return the localised currency format specified in the language bundle */ private static final NumberFormat getCurrencyFormat() { NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(); try { currencyFormat.setCurrency(Currency.getInstance(getI18NString(FrontlineSMSConstants.COMMON_CURRENCY))); } catch(IllegalArgumentException ex) { LOG.warn("Currency not supported: " + getI18NString(FrontlineSMSConstants.COMMON_CURRENCY), ex); } return currencyFormat; } //> LANGUAGE BUNDLE LOADING METHODS /** * Loads the default, english {@link LanguageBundle} from the classpath * @return the default English {@link LanguageBundle} * @throws IOException If there was a problem loading the default language bundle. // TODO this should probably throw a runtimeexception of some sort */ public static final LanguageBundle getDefaultLanguageBundle() throws IOException { return ClasspathLanguageBundle.create(DEFAULT_LANGUAGE_BUNDLE_PATH); } /** @return {@link InputStream} to the default translation file on the classpath. */ public static InputStream getDefaultLanguageBundleInputStream() { return ClasspathLanguageBundle.class.getResourceAsStream(DEFAULT_LANGUAGE_BUNDLE_PATH); } /** * Loads a {@link LanguageBundle} from a file. All files are encoded with UTF-8. * TODO change this to use {@link Currency}, and put the ISO 4217 currency code in the l10n file. * @param file * @return The loaded bundle, or NULL if the bundle could not be loaded. */ public static final FileLanguageBundle getLanguageBundle(File file) { try { FileLanguageBundle bundle = FileLanguageBundle.create(file); LOG.info("Successfully loaded language bundle from file: " + file.getName()); LOG.info("Bundle reports filename as: " + bundle.getFile().getAbsolutePath()); LOG.info("Language Name : " + bundle.getLanguageName()); LOG.info("Language Code : " + bundle.getLanguageCode()); LOG.info("Country : " + bundle.getCountry()); LOG.info("Right-To-Left : " + bundle.isRightToLeft()); return bundle; } catch(Exception ex) { LOG.error("Problem reading language file: " + file.getName(), ex); return null; } } /** * @param identifier ID used when logging problems while loading the text resource * @param inputStream * @return map containing map of key-value pairs of text resources * @throws IOException */ public static final Map<String, String> loadTextResources(String identifier, InputStream inputStream) throws IOException { HashMap<String, String> i18nStrings = new HashMap<String, String>(); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, CHARSET_UTF8)); String line; while((line = in.readLine()) != null) { line = line.trim(); if(line.length() > 0 && line.charAt(0) != '#') { int splitChar = line.indexOf('='); if(splitChar <= 0) { // there's no "key=value" pair on this line, but it does have text on it. That's // not strictly legal, so we'll log a warning and carry on. LOG.warn("Bad line in language file '" + identifier + "': '" + line + "'"); } else { String key = line.substring(0, splitChar).trim(); if(i18nStrings.containsKey(key)) { // This key has already been read from the language file. Ignore the new value. LOG.warn("Duplicate key in language file '': ''"); } else { String value = line.substring(splitChar + 1).trim(); - i18nStrings.put(key, value); + if (!value.equals("")) { + i18nStrings.put(key, value); + } } } } } return i18nStrings; } /** * Loads all language bundles from within and without the JAR * @return all language bundles from within and without the JAR */ public static Collection<FileLanguageBundle> getLanguageBundles() { ArrayList<FileLanguageBundle> bundles = new ArrayList<FileLanguageBundle>(); File langDir = new File(getLanguageDirectoryPath()); if(!langDir.exists() || !langDir.isDirectory()) throw new IllegalArgumentException("Could not find resources directory: " + langDir.getAbsolutePath()); for (File file : langDir.listFiles()) { FileLanguageBundle bungle = getLanguageBundle(file); if(bungle != null) { bundles.add(bungle); } } return bundles; } /** @return path of the directory in which language bundles are located. */ private static final String getLanguageDirectoryPath() { return ResourceUtils.getConfigDirectoryPath() + LANGUAGES_DIRECTORY_NAME + File.separatorChar; } /** @return path of the directory in which language bundles are located. */ public static final File getLanguageDirectory() { return new File(ResourceUtils.getConfigDirectoryPath(), LANGUAGES_DIRECTORY_NAME); } //> DATE FORMAT GETTERS /** * N.B. This {@link DateFormat} may be used for parsing user-entered data. * @return date format for displaying and entering year (4 digits), month and day. */ public static DateFormat getDateFormat() { return new SimpleDateFormat(getI18NString(FrontlineSMSConstants.DATEFORMAT_YMD)); } /** * This is not used for parsing user-entered data. * @return date format for displaying date and time.# */ public static DateFormat getDatetimeFormat() { return new SimpleDateFormat(getI18NString(FrontlineSMSConstants.DATEFORMAT_YMD_HMS)); } /** * TODO what is this method used for? This value seems completely nonsensical - why wouldn't you just use the timestamp itself? When do you ever need the date as an actual string? * @return current time as a formatted date string */ public static String getDefaultStartDate() { return getDateFormat().format(new Date()); } /** * Parse the supplied {@link String} into a {@link Date}. * This method assumes that the supplied date is in the same format as {@link #getDateFormat()}. * @param date A date {@link String} formatted with {@link #getDateFormat()} * @return a java {@link Date} object describing the supplied date * @throws ParseException */ public static Date parseDate(String date) throws ParseException { return getDateFormat().parse(date); } /** * <p>Merges the source map into the destination. Values in the destination take precedence - they will not be * overridden if the same key occurs in both destination and source.</p> * <p>If a <code>null</code> source is provided, this method does nothing; if a <code>null</code> destination is * provided, a {@link NullPointerException} will be thrown. * @param destination * @param source */ public static void mergeMaps(Map<String, String> destination, Map<String, String> source) { assert(destination!=null): "You must provide a destination map to merge into."; // If there is nothing to merge, just return. if(source == null) return; for(String key : source.keySet()) { if(destination.get(key) != null) { // key already present in language bundle - ignoring } else { // this key does not appear in the language bundle, so add it with the value from the map destination.put(key, source.get(key)); } } } /** * Get the status of a {@link Email} as a {@link String}. * @param email * @return {@link String} representation of the status. */ public static final String getEmailStatusAsString(Email email) { switch(email.getStatus()) { case OUTBOX: return getI18NString(COMMON_OUTBOX); case PENDING: return getI18NString(COMMON_PENDING); case SENT: return getI18NString(COMMON_SENT); case RETRYING: return getI18NString(COMMON_RETRYING); case FAILED: return getI18NString(COMMON_FAILED); default: return "(unknown)"; } } }
true
true
public static final Map<String, String> loadTextResources(String identifier, InputStream inputStream) throws IOException { HashMap<String, String> i18nStrings = new HashMap<String, String>(); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, CHARSET_UTF8)); String line; while((line = in.readLine()) != null) { line = line.trim(); if(line.length() > 0 && line.charAt(0) != '#') { int splitChar = line.indexOf('='); if(splitChar <= 0) { // there's no "key=value" pair on this line, but it does have text on it. That's // not strictly legal, so we'll log a warning and carry on. LOG.warn("Bad line in language file '" + identifier + "': '" + line + "'"); } else { String key = line.substring(0, splitChar).trim(); if(i18nStrings.containsKey(key)) { // This key has already been read from the language file. Ignore the new value. LOG.warn("Duplicate key in language file '': ''"); } else { String value = line.substring(splitChar + 1).trim(); i18nStrings.put(key, value); } } } } return i18nStrings; }
public static final Map<String, String> loadTextResources(String identifier, InputStream inputStream) throws IOException { HashMap<String, String> i18nStrings = new HashMap<String, String>(); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, CHARSET_UTF8)); String line; while((line = in.readLine()) != null) { line = line.trim(); if(line.length() > 0 && line.charAt(0) != '#') { int splitChar = line.indexOf('='); if(splitChar <= 0) { // there's no "key=value" pair on this line, but it does have text on it. That's // not strictly legal, so we'll log a warning and carry on. LOG.warn("Bad line in language file '" + identifier + "': '" + line + "'"); } else { String key = line.substring(0, splitChar).trim(); if(i18nStrings.containsKey(key)) { // This key has already been read from the language file. Ignore the new value. LOG.warn("Duplicate key in language file '': ''"); } else { String value = line.substring(splitChar + 1).trim(); if (!value.equals("")) { i18nStrings.put(key, value); } } } } } return i18nStrings; }
diff --git a/src/main/java/hudson/plugins/plot/Plot.java b/src/main/java/hudson/plugins/plot/Plot.java index 3da33c0..cb23db2 100644 --- a/src/main/java/hudson/plugins/plot/Plot.java +++ b/src/main/java/hudson/plugins/plot/Plot.java @@ -1,822 +1,824 @@ /* * Copyright (c) 2007-2009 Yahoo! Inc. All rights reserved. * The copyrights to the contents of this file are licensed under the MIT License (http://www.opensource.org/licenses/mit-license.php) */ package hudson.plugins.plot; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Build; import hudson.model.Project; import hudson.model.Run; import hudson.util.ChartUtil; import hudson.util.ShiftedCategoryAxis; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Polygon; import java.awt.Shape; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Random; import java.util.logging.Logger; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartRenderingInfo; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.CategoryLabelPositions; import org.jfree.chart.labels.StandardCategoryToolTipGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.DefaultDrawingSupplier; import org.jfree.chart.plot.DrawingSupplier; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.AbstractCategoryItemRenderer; import org.jfree.chart.renderer.category.LineAndShapeRenderer; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.CSVWriter; /** * Represents the configuration for a single plot. A plot can * have one or more data series (lines). Each data series * has one data point per build. The x-axis is always the * build number. * * A plot has the following characteristics: * <ul> * <li> a title (mandatory) * <li> y-axis label (defaults to no label) * <li> one or more data series * <li> plot group (defaults to no group) * <li> number of builds to show on the plot (defaults to all) * </ul> * * A plots group effects the way in which plots are displayed. Group names * are listed as links on the top-level plot page. The user then clicks * on a group and sees the plots that belong to that group. * * @author Nigel Daley */ public class Plot implements Comparable { private static final Logger LOGGER = Logger.getLogger(Plot.class.getName()); private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MMM d"); /** * Effectively a 2-dimensional array, where each row is the * data for one data series of an individual build; the columns * are: series y-value, series label, build number, optional URL */ private transient ArrayList<String[]> rawPlotData; /** * The generated plot, which is only regenerated when new data * is added (it is re-rendered, however, every time it is requested). */ private transient JFreeChart plot; /** * The project (or job) that this plot belongs to. A reference * to the project is needed to retrieve and save the CSV file * that is stored in the project's root directory. */ private transient AbstractProject project; /** All plots share the same JFreeChart drawing supplier object. */ private static final DrawingSupplier supplier = new DefaultDrawingSupplier( DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE, DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE, DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE, DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE, // the plot data points are a small diamond shape new Shape[] { new Polygon(new int[] {3, 0, -3, 0}, new int[] {0, 4, 0, -4}, 4) } ); /** The default plot width. */ private static final int DEFAULT_WIDTH = 750; /** The default plot height. */ private static final int DEFAULT_HEIGHT = 450; /** The default number of builds on plot (all). */ private static final String DEFAULT_NUMBUILDS = ""; // Transient values /** The width of the plot. */ private transient int width; /** The height of the plot. */ private transient int height; /** The right-most build number on the plot. */ private transient int rightBuildNum; /** Whether or not the plot has a legend. */ private transient boolean hasLegend = true; /** Number of builds back to show on this plot from url. */ public transient String urlNumBuilds; /** Title of plot from url. */ public transient String urlTitle; /** Style of plot from url. */ public transient String urlStyle; /** Use description flag from url. */ public transient Boolean urlUseDescr; // Configuration values /** Title of plot. Mandatory. */ public String title; /** Y-axis label. Optional. */ public String yaxis; /** Array of data series. */ public Series[] series; /** Group name that this plot belongs to. */ public String group; /** * Number of builds back to show on this plot. * Empty string means all builds. Must not be "0". */ public String numBuilds; /** * The name of the CSV file that persists the plots data. * The CSV file is stored in the projects root directory. * This is different from the source csv file that can be used as a source for the plot. */ public String csvFileName; /** The date of the last change to the CSV file. */ private long csvLastModification; /** Optional style of plot: line, line3d, stackedArea, stackedBar, etc. */ public String style; /** Whether or not to use build descriptions as X-axis labels. Optional. */ public boolean useDescr; /** * Creates a new plot with the given paramenters. If numBuilds * is the empty string, then all builds will be included. Must * not be zero. */ @DataBoundConstructor public Plot(String title, String yaxis, String group, String numBuilds, String csvFileName, String style, boolean useDescr) { this.title = title; this.yaxis = yaxis; this.group = group; this.numBuilds = numBuilds; if (csvFileName == null || csvFileName.trim().length()==0) { //TODO: check project dir to ensure uniqueness instead of just random csvFileName = Math.abs(new Random().nextInt()) + ".csv"; } this.csvFileName = csvFileName; this.style = style; this.useDescr = useDescr; } // needed for serialization public Plot() {} public int compareTo(Object o) { return title.compareTo(((Plot)o).getTitle()); } @Override public String toString() { return "TITLE("+getTitle()+ "),YAXIS("+yaxis+ "),NUMSERIES("+series.length+ "),GROUP("+group+ "),NUMBUILDS("+numBuilds+ "),RIGHTBUILDNUM("+getRightBuildNum()+ "),HASLEGEND("+hasLegend()+ "),FILENAME("+csvFileName+")"; } public String getYaxis() { return yaxis; } public Series[] getSeries() { return series; } public String getGroup() { return group; } public String getCsvFileName() { return csvFileName; } /** * Sets the title for the plot from the "title" parameter * in the given StaplerRequest. */ private void setTitle(StaplerRequest req) { urlTitle = req.getParameter("title"); } private String getURLTitle() { return urlTitle != null ? urlTitle : title; } public String getTitle() { return title; } private void setStyle(StaplerRequest req) { urlStyle = req.getParameter("style"); } private String getUrlStyle() { return urlStyle != null ? urlStyle : (style != null ? style : ""); } private void setUseDescr(StaplerRequest req) { String u = req.getParameter("usedescr"); if (u == null) { urlUseDescr = null; } else { urlUseDescr = u.equalsIgnoreCase("on") || u.equalsIgnoreCase("true"); } } private boolean getUrlUseDescr() { return urlUseDescr != null ? urlUseDescr : useDescr; } /** * Sets the number of builds to plot from the "numbuilds" parameter * in the given StaplerRequest. If the parameter doesn't exist * or isn't an integer then a default is used. */ private void setHasLegend(StaplerRequest req) { String legend = req.getParameter("legend"); hasLegend = legend == null || legend.equalsIgnoreCase("on") || legend.equalsIgnoreCase("true"); } public boolean hasLegend() { return hasLegend; } /** * Sets the number of builds to plot from the "numbuilds" parameter * in the given StaplerRequest. If the parameter doesn't exist * or isn't an integer then a default is used. */ private void setNumBuilds(StaplerRequest req) { urlNumBuilds = req.getParameter("numbuilds"); if (urlNumBuilds != null) { try { // simply try and parse the string to see if it's a valid number, throw away the result. } catch (NumberFormatException nfe) { urlNumBuilds = null; } } } public String getURLNumBuilds() { return urlNumBuilds != null ? urlNumBuilds : numBuilds; } public String getNumBuilds() { return numBuilds; } /** * Sets the right-most build number shown on the plot from * the "rightbuildnum" parameter in the given StaplerRequest. * If the parameter doesn't exist or isn't an integer then * a default is used. */ private void setRightBuildNum(StaplerRequest req) { String build = req.getParameter("rightbuildnum"); if (build == null) { rightBuildNum = Integer.MAX_VALUE; } else { try { rightBuildNum = Integer.parseInt(build); } catch (NumberFormatException nfe) { rightBuildNum = Integer.MAX_VALUE; } } } private int getRightBuildNum() { return rightBuildNum; } /** * Sets the plot width from the "width" parameter in the * given StaplerRequest. If the parameter doesn't exist * or isn't an integer then a default is used. */ private void setWidth(StaplerRequest req) { String w = req.getParameter("width"); if (w == null) { width = DEFAULT_WIDTH; } else { try { width = Integer.parseInt(w); } catch (NumberFormatException nfe) { width = DEFAULT_WIDTH; } } } private int getWidth() { return width; } /** * Sets the plot height from the "height" parameter in the * given StaplerRequest. If the parameter doesn't exist * or isn't an integer then a default is used. */ private void setHeight(StaplerRequest req) { String h = req.getParameter("height"); if (h == null) { height = DEFAULT_HEIGHT; } else { try { height = Integer.parseInt(h); } catch (NumberFormatException nfe) { height = DEFAULT_HEIGHT; } } } private int getHeight() { return height; } /** * A reference to the project is needed to retrieve * the project's root directory where the CSV file * is located. Unfortunately, a reference to the project * is not available when this object is created. * * @param project the project */ public void setProject(Project project) { this.project = project; } /** * Generates and writes the plot to the response output stream. * * @param req the incoming request * @param rsp the response stream * @throws IOException */ public void plotGraph(StaplerRequest req, StaplerResponse rsp) throws IOException { if (ChartUtil.awtProblemCause != null) { // Not available. Send out error message. rsp.sendRedirect2(req.getContextPath()+"/images/headless.png"); return; } setWidth(req); setHeight(req); setNumBuilds(req); setRightBuildNum(req); setHasLegend(req); setTitle(req); setStyle(req); setUseDescr(req); // need to force regenerate the plot in case build // descriptions (used for tool tips) have changed generatePlot(true); ChartUtil.generateGraph(req, rsp, plot, getWidth(), getHeight()); } /** * Generates and writes the plot's clickable map to the response * output stream. * * @param req the incoming request * @param rsp the response stream * @throws IOException */ public void plotGraphMap(StaplerRequest req, StaplerResponse rsp) throws IOException { if (ChartUtil.awtProblemCause != null) { // not available. send out error message rsp.sendRedirect2(req.getContextPath()+"/images/headless.png"); return; } setWidth(req); setHeight(req); setNumBuilds(req); setRightBuildNum(req); setHasLegend(req); setTitle(req); setStyle(req); setUseDescr(req); generatePlot(false); ChartRenderingInfo info = new ChartRenderingInfo(); plot.createBufferedImage(getWidth(),getHeight(),info); rsp.setContentType("text/plain;charset=UTF-8"); rsp.getWriter().println(ChartUtilities.getImageMap(getCsvFileName(),info)); } /** * Called when a build completes. Adds the finished build to this plot. * This method extracts the data for each data series from the build and * saves it in the plot's CSV file. * * @param build * @param logger */ public void addBuild(Build build, PrintStream logger) { if (project == null) project = build.getProject(); // load the existing plot data from disk loadPlotData(); // extract the data for each data series for (Series series : getSeries()) { if (series == null) continue; PlotPoint[] seriesData = series.loadSeries(build.getWorkspace(),logger); if (seriesData != null) { for (PlotPoint point : seriesData) { if (point == null) continue; rawPlotData.add(new String[] { point.getYvalue(), point.getLabel(), build.getNumber() + "", // convert to a string build.getTimestamp().getTimeInMillis() + "", point.getUrl() }); } } } // save the updated plot data to disk savePlotData(); // currently only support for csv type if (getSeries() != null) { Series series = getSeries()[0]; if ("csv".equals(series.getFileType())) { saveTableData(build, series.getFile()); } } } /** * Generates the plot and stores it in the plot instance variable. * * @param forceGenerate if true, force the plot to be re-generated * even if the on-disk data hasn't changed */ private void generatePlot(boolean forceGenerate) { class Label implements Comparable<Label> { final private Integer buildNum; final private String buildDate; final private String text; public Label(String buildNum, String buildTime, String text) { this.buildNum = Integer.parseInt(buildNum); - this.buildDate = DATE_FORMAT.format( - new Date(Long.parseLong(buildTime))); + synchronized (DATE_FORMAT) { + this.buildDate = DATE_FORMAT.format( + new Date(Long.parseLong(buildTime))); + } this.text = text; } public Label(String buildNum, String buildTime) { this(buildNum, buildTime, null); } public int compareTo(Label that) { return this.buildNum - that.buildNum; } @Override public boolean equals(Object o) { return o instanceof Label && ((Label) o).buildNum.equals(buildNum); } @Override public int hashCode() { return buildNum.hashCode(); } public String numDateString() { return "#" + buildNum + " (" + buildDate + ")"; } @Override public String toString() { return text != null ? text : numDateString(); } } //LOGGER.info("Determining if we should generate plot " + getCsvFileName()); File csvFile = new File(project.getRootDir(),getCsvFileName()); if (csvFile.lastModified() == csvLastModification && plot != null && !forceGenerate) { // data hasn't changed so don't regenerate the plot return; } if (rawPlotData == null || csvFile.lastModified() > csvLastModification) { // data has changed or has not been loaded so load it now loadPlotData(); } //LOGGER.info("Generating plot " + getCsvFileName()); csvLastModification = csvFile.lastModified(); PlotCategoryDataset dataset = new PlotCategoryDataset(); for (String[] record : rawPlotData) { // record: series y-value, series label, build number, build date, url int buildNum; try { buildNum = Integer.valueOf(record[2]); if (buildNum > getRightBuildNum()) { continue; // skip this record } } catch (NumberFormatException nfe) { continue; // skip this record all together } Number value = null; try { value = Integer.valueOf(record[0]); } catch (NumberFormatException nfe) { try { value = Double.valueOf(record[0]); } catch (NumberFormatException nfe2) { continue; // skip this record all together } } String series = record[1]; Label xlabel = getUrlUseDescr() ? new Label(record[2], record[3], descriptionForBuild(buildNum)) : new Label(record[2], record[3]); String url = null; if (record.length >= 5) url = record[4]; dataset.setValue(value, url, series, xlabel); } int numBuilds; try { numBuilds = Integer.parseInt(getURLNumBuilds()); } catch (NumberFormatException nfe) { numBuilds = Integer.MAX_VALUE; } dataset.clipDataset(numBuilds); plot = createChart(dataset); CategoryPlot categoryPlot = (CategoryPlot) plot.getPlot(); categoryPlot.setDomainGridlinePaint(Color.black); categoryPlot.setRangeGridlinePaint(Color.black); categoryPlot.setDrawingSupplier(Plot.supplier); CategoryAxis domainAxis = new ShiftedCategoryAxis(Messages.Plot_Build()); categoryPlot.setDomainAxis(domainAxis); domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90); domainAxis.setLowerMargin(0.0); domainAxis.setUpperMargin(0.03); domainAxis.setCategoryMargin(0.0); for (Object category : dataset.getColumnKeys()) { Label label = (Label) category; if (label.text != null) { domainAxis.addCategoryLabelToolTip(label, label.numDateString()); } else { domainAxis.addCategoryLabelToolTip(label, descriptionForBuild(label.buildNum)); } } AbstractCategoryItemRenderer renderer = (AbstractCategoryItemRenderer) categoryPlot.getRenderer(); int numColors = dataset.getRowCount(); for (int i = 0; i < numColors; i++) { renderer.setSeriesPaint(i, new Color(Color.HSBtoRGB( (1f / numColors) * i, 1f, 1f))); } renderer.setStroke(new BasicStroke(2.0f)); renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator( Messages.Plot_Build() + " {1}: {2}", NumberFormat.getInstance())); renderer.setItemURLGenerator(new PointURLGenerator()); if (renderer instanceof LineAndShapeRenderer) { LineAndShapeRenderer lasRenderer = (LineAndShapeRenderer) renderer; lasRenderer.setShapesVisible(true); // TODO: deprecated, may be unnecessary } } /** * Creates a Chart of the style indicated by getEffStyle() using the given dataset. * Defaults to using createLineChart. */ private JFreeChart createChart(PlotCategoryDataset dataset) { String s = getUrlStyle(); if (s.equalsIgnoreCase("area")) { return ChartFactory.createAreaChart( getURLTitle(), /*categoryAxisLabel=*/null, getYaxis(), dataset, PlotOrientation.VERTICAL, hasLegend(), /*tooltips=*/true, /*url=*/false); } if (s.equalsIgnoreCase("bar")) { return ChartFactory.createBarChart( getURLTitle(), /*categoryAxisLabel=*/null, getYaxis(), dataset, PlotOrientation.VERTICAL, hasLegend(), /*tooltips=*/true, /*url=*/false); } if (s.equalsIgnoreCase("bar3d")) { return ChartFactory.createBarChart3D( getURLTitle(), /*categoryAxisLabel=*/null, getYaxis(), dataset, PlotOrientation.VERTICAL, hasLegend(), /*tooltips=*/true, /*url=*/false); } if (s.equalsIgnoreCase("line3d")) { return ChartFactory.createLineChart3D( getURLTitle(), /*categoryAxisLabel=*/null, getYaxis(), dataset, PlotOrientation.VERTICAL, hasLegend(), /*tooltips=*/true, /*url=*/false); } if (s.equalsIgnoreCase("stackedarea")) { return ChartFactory.createStackedAreaChart( getURLTitle(), /*categoryAxisLabel=*/null, getYaxis(), dataset, PlotOrientation.VERTICAL, hasLegend(), /*tooltips=*/true, /*url=*/false); } if (s.equalsIgnoreCase("stackedbar")) { return ChartFactory.createStackedBarChart( getURLTitle(), /*categoryAxisLabel=*/null, getYaxis(), dataset, PlotOrientation.VERTICAL, hasLegend(), /*tooltips=*/true, /*url=*/false); } if (s.equalsIgnoreCase("stackedbar3d")) { return ChartFactory.createStackedBarChart3D( getURLTitle(), /*categoryAxisLabel=*/null, getYaxis(), dataset, PlotOrientation.VERTICAL, hasLegend(), /*tooltips=*/true, /*url=*/false); } if (s.equalsIgnoreCase("waterfall")) { return ChartFactory.createWaterfallChart( getURLTitle(), /*categoryAxisLabel=*/null, getYaxis(), dataset, PlotOrientation.VERTICAL, hasLegend(), /*tooltips=*/true, /*url=*/false); } return ChartFactory.createLineChart( getURLTitle(), /*categoryAxisLabel=*/null, getYaxis(), dataset, PlotOrientation.VERTICAL, hasLegend(), /*tooltips=*/true, /*url=*/false); } /** * Returns a trimmed description string for the build specified by the given build number. */ private String descriptionForBuild(int buildNum) { Run r = project.getBuildByNumber(buildNum); if (r != null) { String tip = r.getTruncatedDescription(); if (tip != null) { return tip.replaceAll("<p> *|<br> *", ", "); } } return null; } /** * Loads the plot data from the CSV file on disk. The * CSV file is stored in the projects root directory. * The data is stored in the rawPlotData instance variable. */ private void loadPlotData() { rawPlotData = new ArrayList<String[]>(); // load existing plot file File plotFile = new File(project.getRootDir(),getCsvFileName()); if (!plotFile.exists()) { return; } CSVReader reader = null; rawPlotData = new ArrayList<String[]>(); try { reader = new CSVReader(new FileReader(plotFile)); // throw away 2 header lines reader.readNext(); reader.readNext(); // read each line of the CSV file and add to rawPlotData String [] nextLine; while ((nextLine = reader.readNext()) != null) { rawPlotData.add(nextLine); } } catch (IOException ioe) { //ignore } finally { if (reader != null) { try { reader.close(); } catch (IOException ignore) { //ignore } } } } /** * Saves the plot data to the CSV file on disk. The * CSV file is stored in the projects root directory. * The data is read from the rawPlotData instance variable. */ private void savePlotData() { File plotFile = new File(project.getRootDir(),getCsvFileName()); CSVWriter writer = null; try { writer = new CSVWriter(new FileWriter(plotFile)); // write 2 header lines String[] header1 = new String[] {Messages.Plot_Title(),this.getTitle()}; String[] header2 = new String[] {Messages.Plot_Value(), Messages.Plot_SeriesLabel(), Messages.Plot_BuildNumber(), Messages.Plot_BuildDate(), Messages.Plot_URL()}; writer.writeNext(header1); writer.writeNext(header2); // write each entry of rawPlotData to a new line in the CSV file for (String[] entry : rawPlotData) { writer.writeNext(entry); } } catch (IOException ioe) { //ignore } finally { if (writer != null) { try { writer.close(); } catch (IOException ignore) { //ignore } } } } private void saveTableData(AbstractBuild<?,?> build, String fileName) { ArrayList rawTableData = new ArrayList(); File tableFile = new File(project.getRootDir(), "table_"+getCsvFileName()); File rawCSVFile = new File(build.getWorkspace() + File.separator + fileName); CSVReader existingTableReader = null; CSVReader newTupleReader = null; CSVWriter newTableWriter = null; try { newTupleReader = new CSVReader(new FileReader(rawCSVFile)); // new header including build # String [] header = newTupleReader.readNext(); String [] headerIncBuild = new String [header.length+1]; headerIncBuild[0] = Messages.Plot_build() + " #"; System.arraycopy(header, 0, headerIncBuild, 1, header.length); // add a new tuple String [] tuple = newTupleReader.readNext(); String [] tupleIncBuild = new String [tuple.length+1]; tupleIncBuild[0] = ""+ build.getNumber(); System.arraycopy(tuple, 0, tupleIncBuild, 1, tuple.length); rawTableData.add (tupleIncBuild); // load existing data if (tableFile.exists()) { existingTableReader = new CSVReader(new FileReader(tableFile)); // skip header existingTableReader.readNext(); int numBuilds; try { numBuilds = Integer.parseInt(getNumBuilds()); } catch (NumberFormatException nfe) { numBuilds = Integer.MAX_VALUE; } String [] nextLine; int count = 0; while ((nextLine = existingTableReader.readNext()) != null && count++ < numBuilds-1) { rawTableData.add(nextLine); } } // write to CSV file newTableWriter = new CSVWriter(new FileWriter(tableFile)); newTableWriter.writeNext(headerIncBuild); newTableWriter.writeAll(rawTableData); } catch (IOException ioe) { //ignore } finally { if (existingTableReader != null) { try { existingTableReader.close(); } catch (IOException ignore) { //ignore } } if (newTupleReader != null) { try { newTupleReader.close(); } catch (IOException ignore) { //ignore } } if (newTableWriter != null) { try { newTableWriter.close(); } catch (IOException ignore) { //ignore } } } } }
true
true
private void generatePlot(boolean forceGenerate) { class Label implements Comparable<Label> { final private Integer buildNum; final private String buildDate; final private String text; public Label(String buildNum, String buildTime, String text) { this.buildNum = Integer.parseInt(buildNum); this.buildDate = DATE_FORMAT.format( new Date(Long.parseLong(buildTime))); this.text = text; } public Label(String buildNum, String buildTime) { this(buildNum, buildTime, null); } public int compareTo(Label that) { return this.buildNum - that.buildNum; } @Override public boolean equals(Object o) { return o instanceof Label && ((Label) o).buildNum.equals(buildNum); } @Override public int hashCode() { return buildNum.hashCode(); } public String numDateString() { return "#" + buildNum + " (" + buildDate + ")"; } @Override public String toString() { return text != null ? text : numDateString(); } } //LOGGER.info("Determining if we should generate plot " + getCsvFileName()); File csvFile = new File(project.getRootDir(),getCsvFileName()); if (csvFile.lastModified() == csvLastModification && plot != null && !forceGenerate) { // data hasn't changed so don't regenerate the plot return; } if (rawPlotData == null || csvFile.lastModified() > csvLastModification) { // data has changed or has not been loaded so load it now loadPlotData(); } //LOGGER.info("Generating plot " + getCsvFileName()); csvLastModification = csvFile.lastModified(); PlotCategoryDataset dataset = new PlotCategoryDataset(); for (String[] record : rawPlotData) { // record: series y-value, series label, build number, build date, url int buildNum; try { buildNum = Integer.valueOf(record[2]); if (buildNum > getRightBuildNum()) { continue; // skip this record } } catch (NumberFormatException nfe) { continue; // skip this record all together } Number value = null; try { value = Integer.valueOf(record[0]); } catch (NumberFormatException nfe) { try { value = Double.valueOf(record[0]); } catch (NumberFormatException nfe2) { continue; // skip this record all together } } String series = record[1]; Label xlabel = getUrlUseDescr() ? new Label(record[2], record[3], descriptionForBuild(buildNum)) : new Label(record[2], record[3]); String url = null; if (record.length >= 5) url = record[4]; dataset.setValue(value, url, series, xlabel); } int numBuilds; try { numBuilds = Integer.parseInt(getURLNumBuilds()); } catch (NumberFormatException nfe) { numBuilds = Integer.MAX_VALUE; } dataset.clipDataset(numBuilds); plot = createChart(dataset); CategoryPlot categoryPlot = (CategoryPlot) plot.getPlot(); categoryPlot.setDomainGridlinePaint(Color.black); categoryPlot.setRangeGridlinePaint(Color.black); categoryPlot.setDrawingSupplier(Plot.supplier); CategoryAxis domainAxis = new ShiftedCategoryAxis(Messages.Plot_Build()); categoryPlot.setDomainAxis(domainAxis); domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90); domainAxis.setLowerMargin(0.0); domainAxis.setUpperMargin(0.03); domainAxis.setCategoryMargin(0.0); for (Object category : dataset.getColumnKeys()) { Label label = (Label) category; if (label.text != null) { domainAxis.addCategoryLabelToolTip(label, label.numDateString()); } else { domainAxis.addCategoryLabelToolTip(label, descriptionForBuild(label.buildNum)); } } AbstractCategoryItemRenderer renderer = (AbstractCategoryItemRenderer) categoryPlot.getRenderer(); int numColors = dataset.getRowCount(); for (int i = 0; i < numColors; i++) { renderer.setSeriesPaint(i, new Color(Color.HSBtoRGB( (1f / numColors) * i, 1f, 1f))); } renderer.setStroke(new BasicStroke(2.0f)); renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator( Messages.Plot_Build() + " {1}: {2}", NumberFormat.getInstance())); renderer.setItemURLGenerator(new PointURLGenerator()); if (renderer instanceof LineAndShapeRenderer) { LineAndShapeRenderer lasRenderer = (LineAndShapeRenderer) renderer; lasRenderer.setShapesVisible(true); // TODO: deprecated, may be unnecessary } }
private void generatePlot(boolean forceGenerate) { class Label implements Comparable<Label> { final private Integer buildNum; final private String buildDate; final private String text; public Label(String buildNum, String buildTime, String text) { this.buildNum = Integer.parseInt(buildNum); synchronized (DATE_FORMAT) { this.buildDate = DATE_FORMAT.format( new Date(Long.parseLong(buildTime))); } this.text = text; } public Label(String buildNum, String buildTime) { this(buildNum, buildTime, null); } public int compareTo(Label that) { return this.buildNum - that.buildNum; } @Override public boolean equals(Object o) { return o instanceof Label && ((Label) o).buildNum.equals(buildNum); } @Override public int hashCode() { return buildNum.hashCode(); } public String numDateString() { return "#" + buildNum + " (" + buildDate + ")"; } @Override public String toString() { return text != null ? text : numDateString(); } } //LOGGER.info("Determining if we should generate plot " + getCsvFileName()); File csvFile = new File(project.getRootDir(),getCsvFileName()); if (csvFile.lastModified() == csvLastModification && plot != null && !forceGenerate) { // data hasn't changed so don't regenerate the plot return; } if (rawPlotData == null || csvFile.lastModified() > csvLastModification) { // data has changed or has not been loaded so load it now loadPlotData(); } //LOGGER.info("Generating plot " + getCsvFileName()); csvLastModification = csvFile.lastModified(); PlotCategoryDataset dataset = new PlotCategoryDataset(); for (String[] record : rawPlotData) { // record: series y-value, series label, build number, build date, url int buildNum; try { buildNum = Integer.valueOf(record[2]); if (buildNum > getRightBuildNum()) { continue; // skip this record } } catch (NumberFormatException nfe) { continue; // skip this record all together } Number value = null; try { value = Integer.valueOf(record[0]); } catch (NumberFormatException nfe) { try { value = Double.valueOf(record[0]); } catch (NumberFormatException nfe2) { continue; // skip this record all together } } String series = record[1]; Label xlabel = getUrlUseDescr() ? new Label(record[2], record[3], descriptionForBuild(buildNum)) : new Label(record[2], record[3]); String url = null; if (record.length >= 5) url = record[4]; dataset.setValue(value, url, series, xlabel); } int numBuilds; try { numBuilds = Integer.parseInt(getURLNumBuilds()); } catch (NumberFormatException nfe) { numBuilds = Integer.MAX_VALUE; } dataset.clipDataset(numBuilds); plot = createChart(dataset); CategoryPlot categoryPlot = (CategoryPlot) plot.getPlot(); categoryPlot.setDomainGridlinePaint(Color.black); categoryPlot.setRangeGridlinePaint(Color.black); categoryPlot.setDrawingSupplier(Plot.supplier); CategoryAxis domainAxis = new ShiftedCategoryAxis(Messages.Plot_Build()); categoryPlot.setDomainAxis(domainAxis); domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90); domainAxis.setLowerMargin(0.0); domainAxis.setUpperMargin(0.03); domainAxis.setCategoryMargin(0.0); for (Object category : dataset.getColumnKeys()) { Label label = (Label) category; if (label.text != null) { domainAxis.addCategoryLabelToolTip(label, label.numDateString()); } else { domainAxis.addCategoryLabelToolTip(label, descriptionForBuild(label.buildNum)); } } AbstractCategoryItemRenderer renderer = (AbstractCategoryItemRenderer) categoryPlot.getRenderer(); int numColors = dataset.getRowCount(); for (int i = 0; i < numColors; i++) { renderer.setSeriesPaint(i, new Color(Color.HSBtoRGB( (1f / numColors) * i, 1f, 1f))); } renderer.setStroke(new BasicStroke(2.0f)); renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator( Messages.Plot_Build() + " {1}: {2}", NumberFormat.getInstance())); renderer.setItemURLGenerator(new PointURLGenerator()); if (renderer instanceof LineAndShapeRenderer) { LineAndShapeRenderer lasRenderer = (LineAndShapeRenderer) renderer; lasRenderer.setShapesVisible(true); // TODO: deprecated, may be unnecessary } }
diff --git a/tests/org.jboss.tools.jsf.ui.bot.test/src/org/jboss/tools/jsf/ui/bot/test/smoke/AddRemoveJSFCapabilitiesTest.java b/tests/org.jboss.tools.jsf.ui.bot.test/src/org/jboss/tools/jsf/ui/bot/test/smoke/AddRemoveJSFCapabilitiesTest.java index 802928db3..91134b5f5 100644 --- a/tests/org.jboss.tools.jsf.ui.bot.test/src/org/jboss/tools/jsf/ui/bot/test/smoke/AddRemoveJSFCapabilitiesTest.java +++ b/tests/org.jboss.tools.jsf.ui.bot.test/src/org/jboss/tools/jsf/ui/bot/test/smoke/AddRemoveJSFCapabilitiesTest.java @@ -1,298 +1,298 @@ /******************************************************************************* * Copyright (c) 2007-2009 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributor: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.jsf.ui.bot.test.smoke; import java.io.File; import org.eclipse.swtbot.swt.finder.SWTBot; import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException; import org.eclipse.swtbot.swt.finder.widgets.SWTBotMenu; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem; import org.jboss.tools.jsf.ui.bot.test.JSFAutoTestCase; import org.jboss.tools.ui.bot.ext.SWTJBTExt; import org.jboss.tools.ui.bot.ext.SWTUtilExt; import org.jboss.tools.ui.bot.ext.helper.ContextMenuHelper; import org.jboss.tools.ui.bot.ext.helper.WidgetFinderHelper; import org.jboss.tools.ui.bot.ext.types.IDELabel; import org.jboss.tools.ui.bot.test.WidgetVariables; /** * Test adding and removing JSF Capabilities from/to JSF Project * * @author Vladimir Pakan */ public class AddRemoveJSFCapabilitiesTest extends JSFAutoTestCase { private SWTJBTExt swtJbtExt = null; private SWTUtilExt swtUtilExt = null; public AddRemoveJSFCapabilitiesTest(){ swtJbtExt = new SWTJBTExt(bot); swtUtilExt = new SWTUtilExt(bot); } public void testAddRemoveJSFCapabilities() { boolean jbdsIsRunning = SWTJBTExt.isJBDSRun(bot); removeJSFCapabilities(jbdsIsRunning); addJSFCapabilities(); // Test add/remove JSF capabilities after project is closed and reopened closeOpenJsfProject(); removeJSFCapabilities(jbdsIsRunning); addJSFCapabilities(); // Test import of deleted JSF project deleteJsfProject(); importJsfProject(); } /** * Import existing JSF Project to Workspace */ private void importJsfProject() { String[] parts = System.getProperty("eclipse.commands").split("\n"); int index = 0; for (index = 0;parts.length > index + 1 && !parts[index].equals("-data");index++){ // do nothing just go through } if (parts.length > index + 1){ String webXmlFileLocation = SWTUtilExt.getTestPluginLocation(JBT_TEST_PROJECT_NAME) + File.separator + "WebContent" + File.separator + "WEB-INF" + File.separator + "web.xml"; bot.menu(IDELabel.Menu.FILE).menu(IDELabel.Menu.IMPORT).click(); bot.shell(IDELabel.Shell.IMPORT).activate(); SWTBotTree tree = bot.tree(); delay(); tree.expandNode("Other").select("JSF Project"); bot.button("Next >").click(); bot.shell(IDELabel.Shell.IMPORT_JSF_PROJECT).activate(); bot.textWithLabel("web.xml Location:*").setText(webXmlFileLocation); bot.button(WidgetVariables.NEXT_BUTTON).click(); SWTJBTExt.addServerToServerViewOnWizardPage(bot, JBOSS_SERVER_GROUP, JBOSS_SERVER_TYPE); bot.sleep(1000L); bot.button(IDELabel.Button.FINISH).click(); eclipse.closeWarningWindowIfOpened(true); eclipse.closeOpenAssociatedPerspectiveShellIfOpened(false); // Start Application Server swtJbtExt.startApplicationServer(0); swtJbtExt.runProjectOnServer(JBT_TEST_PROJECT_NAME); // Check Browser Content String browserText = WidgetFinderHelper.browserInEditorText(bot, "Input User Name Page",true); // Stop Application Server and remove Application Server from Server View SWTJBTExt.stopApplicationServer(bot, 0); SWTJBTExt.deleteApplicationServer(bot, 0); assertTrue("Displayed HTML page has wrong content", - (browserText!= null) && (browserText.indexOf("<TITLE>Input User Name Page</TITLE>") > - 1)); + (browserText!= null) && (browserText.toLowerCase().indexOf("<title>input user name page</title>") > - 1)); setException(null); } else{ throw new RuntimeException("eclipse.commands property doesn't contain -data option"); } } /** * Delete JSF Project from workspace */ private void deleteJsfProject() { removeJSFTestProjectFromServers(); openPackageExplorer(); delay(); SWTBot packageExplorer = bot.viewByTitle(WidgetVariables.PACKAGE_EXPLORER) .bot(); SWTBotTree tree = packageExplorer.tree(); delay(); ContextMenuHelper.prepareTreeItemForContextMenu(tree, tree.getTreeItem(JBT_TEST_PROJECT_NAME)); new SWTBotMenu(ContextMenuHelper.getContextMenu(tree, IDELabel.Menu.DELETE, false)).click(); bot.shell("Delete Resources").activate(); bot.button(WidgetVariables.OK_BUTTON).click(); new SWTUtilExt(bot).waitForNonIgnoredJobs(); } /** * Remove JSF Capabilities from JSF Project * @param jbdsIsRunning */ private void removeJSFCapabilities(boolean jbdsIsRunning) { openWebProjects(); delay(); removeJSFTestProjectFromServers(); SWTBot webProjects = bot.viewByTitle(WidgetVariables.WEB_PROJECTS).bot(); SWTBotTree tree = webProjects.tree(); ContextMenuHelper.prepareTreeItemForContextMenu(tree, tree.getTreeItem(JBT_TEST_PROJECT_NAME)); new SWTBotMenu(ContextMenuHelper.getContextMenu(tree, IDELabel.Menu.WEB_PROJECT_JBT_JSF, false)).menu( IDELabel.Menu.JBT_REMOVE_JSF_CAPABILITIES).click(); bot.shell("Confirmation").activate(); bot.button(WidgetVariables.OK_BUTTON).click(); delay(); assertTrue( "Project " + JBT_TEST_PROJECT_NAME + " was not removed from Web Projects view after JSF Capabilities were removed.", !isTreeItemWithinWebProjectsView(JBT_TEST_PROJECT_NAME)); } @Override protected void closeUnuseDialogs() { // not used } @Override protected boolean isUnuseDialogOpened() { return false; } /** * Add JSF Capabilities to JSF Project */ private void addJSFCapabilities() { openPackageExplorer(); delay(); SWTBot packageExplorer = bot.viewByTitle(WidgetVariables.PACKAGE_EXPLORER) .bot(); SWTBotTree tree = packageExplorer.tree(); ContextMenuHelper.prepareTreeItemForContextMenu(tree, tree.getTreeItem(JBT_TEST_PROJECT_NAME)); delay(); try{ new SWTBotMenu(ContextMenuHelper.getContextMenu(tree, IDELabel.Menu.PACKAGE_EXPLORER_JBT, false)).menu( IDELabel.Menu.ADD_JSF_CAPABILITIES).click(); } catch (WidgetNotFoundException wnfe){ // From 3.1.0.RC1 version this menu is moved to Configure submenu new SWTBotMenu(ContextMenuHelper.getContextMenu(tree, IDELabel.Menu.PACKAGE_EXPLORER_CONFIGURE, false)).menu( IDELabel.Menu.ADD_JSF_CAPABILITIES).click(); } bot.shell("Add JSF Capabilities").activate(); bot.button(WidgetVariables.NEXT_BUTTON).click(); bot.button(WidgetVariables.FINISH_BUTTON).click(); delay(); assertTrue("JSF Capabilities were not added to project " + JBT_TEST_PROJECT_NAME, isTreeItemWithinWebProjectsView(JBT_TEST_PROJECT_NAME)); } /** * Return true when Web Projects Tree contains item with label treeItemLabel * * @param treeItemLabel * @return */ private boolean isTreeItemWithinWebProjectsView(String treeItemLabel) { openWebProjects(); SWTBot webProjects = bot.viewByTitle(WidgetVariables.WEB_PROJECTS).bot(); SWTBotTree tree = webProjects.tree(); boolean isTreeItemWithinWebProjectsView = false; try { tree.getTreeItem(JBT_TEST_PROJECT_NAME); isTreeItemWithinWebProjectsView = true; } catch (WidgetNotFoundException e) { isTreeItemWithinWebProjectsView = false; } return isTreeItemWithinWebProjectsView; } /** * Close and reopen JSF test project */ private void closeOpenJsfProject() { openPackageExplorer(); delay(); SWTBot packageExplorer = bot.viewByTitle(WidgetVariables.PACKAGE_EXPLORER) .bot(); SWTBotTree tree = packageExplorer.tree(); ContextMenuHelper.prepareTreeItemForContextMenu(tree, tree.getTreeItem(JBT_TEST_PROJECT_NAME)); new SWTBotMenu(ContextMenuHelper.getContextMenu(tree, IDELabel.Menu.CLOSE_PROJECT, false)).click(); swtUtilExt.waitForNonIgnoredJobs(5*1000L); new SWTBotMenu(ContextMenuHelper.getContextMenu(tree, IDELabel.Menu.OPEN_PROJECT, false)).click(); swtUtilExt.waitForNonIgnoredJobs(5*1000L); } /** * Remove JSF Test Project from all Servers */ private void removeJSFTestProjectFromServers(){ openServerView(); delay(); SWTBot servers = bot.viewByTitle(WidgetVariables.SERVERS) .bot(); SWTBotTree serverTree = servers.tree(); // Expand All for (SWTBotTreeItem serverTreeItem : serverTree.getAllItems()){ serverTreeItem.expand(); // if JSF Test Project is deployed to server remove it int itemIndex = 0; SWTBotTreeItem[] serverTreeItemChildren = serverTreeItem.getItems(); while (itemIndex < serverTreeItemChildren.length && !serverTreeItemChildren[itemIndex].getText().startsWith(JBT_TEST_PROJECT_NAME)){ itemIndex++; } // Server Tree Item has Child with Text equal to JSF TEst Project if (itemIndex < serverTreeItemChildren.length){ ContextMenuHelper.prepareTreeItemForContextMenu(serverTree,serverTreeItemChildren[itemIndex]); new SWTBotMenu(ContextMenuHelper.getContextMenu(serverTree, IDELabel.Menu.REMOVE, false)).click(); bot.shell("Server").activate(); bot.button(WidgetVariables.OK_BUTTON).click(); } } delay(); } }
true
true
private void importJsfProject() { String[] parts = System.getProperty("eclipse.commands").split("\n"); int index = 0; for (index = 0;parts.length > index + 1 && !parts[index].equals("-data");index++){ // do nothing just go through } if (parts.length > index + 1){ String webXmlFileLocation = SWTUtilExt.getTestPluginLocation(JBT_TEST_PROJECT_NAME) + File.separator + "WebContent" + File.separator + "WEB-INF" + File.separator + "web.xml"; bot.menu(IDELabel.Menu.FILE).menu(IDELabel.Menu.IMPORT).click(); bot.shell(IDELabel.Shell.IMPORT).activate(); SWTBotTree tree = bot.tree(); delay(); tree.expandNode("Other").select("JSF Project"); bot.button("Next >").click(); bot.shell(IDELabel.Shell.IMPORT_JSF_PROJECT).activate(); bot.textWithLabel("web.xml Location:*").setText(webXmlFileLocation); bot.button(WidgetVariables.NEXT_BUTTON).click(); SWTJBTExt.addServerToServerViewOnWizardPage(bot, JBOSS_SERVER_GROUP, JBOSS_SERVER_TYPE); bot.sleep(1000L); bot.button(IDELabel.Button.FINISH).click(); eclipse.closeWarningWindowIfOpened(true); eclipse.closeOpenAssociatedPerspectiveShellIfOpened(false); // Start Application Server swtJbtExt.startApplicationServer(0); swtJbtExt.runProjectOnServer(JBT_TEST_PROJECT_NAME); // Check Browser Content String browserText = WidgetFinderHelper.browserInEditorText(bot, "Input User Name Page",true); // Stop Application Server and remove Application Server from Server View SWTJBTExt.stopApplicationServer(bot, 0); SWTJBTExt.deleteApplicationServer(bot, 0); assertTrue("Displayed HTML page has wrong content", (browserText!= null) && (browserText.indexOf("<TITLE>Input User Name Page</TITLE>") > - 1)); setException(null); } else{ throw new RuntimeException("eclipse.commands property doesn't contain -data option"); } }
private void importJsfProject() { String[] parts = System.getProperty("eclipse.commands").split("\n"); int index = 0; for (index = 0;parts.length > index + 1 && !parts[index].equals("-data");index++){ // do nothing just go through } if (parts.length > index + 1){ String webXmlFileLocation = SWTUtilExt.getTestPluginLocation(JBT_TEST_PROJECT_NAME) + File.separator + "WebContent" + File.separator + "WEB-INF" + File.separator + "web.xml"; bot.menu(IDELabel.Menu.FILE).menu(IDELabel.Menu.IMPORT).click(); bot.shell(IDELabel.Shell.IMPORT).activate(); SWTBotTree tree = bot.tree(); delay(); tree.expandNode("Other").select("JSF Project"); bot.button("Next >").click(); bot.shell(IDELabel.Shell.IMPORT_JSF_PROJECT).activate(); bot.textWithLabel("web.xml Location:*").setText(webXmlFileLocation); bot.button(WidgetVariables.NEXT_BUTTON).click(); SWTJBTExt.addServerToServerViewOnWizardPage(bot, JBOSS_SERVER_GROUP, JBOSS_SERVER_TYPE); bot.sleep(1000L); bot.button(IDELabel.Button.FINISH).click(); eclipse.closeWarningWindowIfOpened(true); eclipse.closeOpenAssociatedPerspectiveShellIfOpened(false); // Start Application Server swtJbtExt.startApplicationServer(0); swtJbtExt.runProjectOnServer(JBT_TEST_PROJECT_NAME); // Check Browser Content String browserText = WidgetFinderHelper.browserInEditorText(bot, "Input User Name Page",true); // Stop Application Server and remove Application Server from Server View SWTJBTExt.stopApplicationServer(bot, 0); SWTJBTExt.deleteApplicationServer(bot, 0); assertTrue("Displayed HTML page has wrong content", (browserText!= null) && (browserText.toLowerCase().indexOf("<title>input user name page</title>") > - 1)); setException(null); } else{ throw new RuntimeException("eclipse.commands property doesn't contain -data option"); } }
diff --git a/modules/shell/src/main/java/org/novelang/outfit/shell/AgentFileInstaller.java b/modules/shell/src/main/java/org/novelang/outfit/shell/AgentFileInstaller.java index 7df72e9d..498e78d7 100644 --- a/modules/shell/src/main/java/org/novelang/outfit/shell/AgentFileInstaller.java +++ b/modules/shell/src/main/java/org/novelang/outfit/shell/AgentFileInstaller.java @@ -1,196 +1,202 @@ /* * Copyright (C) 2008 Laurent Caillette * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.novelang.outfit.shell; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.MissingResourceException; import java.util.regex.Pattern; import com.google.common.base.Charsets; import com.google.common.io.Resources; import org.novelang.logger.Logger; import org.novelang.logger.LoggerFactory; import org.apache.commons.io.FileUtils; /** * Installs the jar of the {@link org.novelang.outfit.shell.insider.InsiderAgent} somewhere * on the local filesystem. * The JVM installs agents from plain jar files. * <p> * This class applies the * <a href="http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom">Initialization on demand idiom</a>. * * @author Laurent Caillette */ public class AgentFileInstaller { private static final Logger LOGGER = LoggerFactory.getLogger( AgentFileInstaller.class ) ; /** * Name of the system property to set the agent jar file externally. * This is useful when running tests from an IDE. * The "{@value #VERSION_PLACEHOLDER}" substring evaluates to */ public static final String AGENTJARFILE_SYSTEMPROPERTYNAME = "org.novelang.outfit.shell.agentjarfile" ; private static final String VERSION_PLACEHOLDER = "${project.version}" ; private static final String DEFAULT_VERSION = "SNAPSHOT" ; /** * Name of the system property to set the version overriding the content of the * {@value #VERSION_RESOURCE_NAME} resource. */ public static final String VERSIONOVERRIDE_SYSTEMPROPERTYNAME = "org.novelang.outfit.shell.versionoverride" ; /** * Version of the embedded jar. Needed to find its resource name. */ private final String version ; private final File jarFile ; public static final String VERSION_PLACEHOLDER_REGEX = Pattern.quote( VERSION_PLACEHOLDER ); public static boolean mayHaveValidInstance() { return System.getProperty( VERSIONOVERRIDE_SYSTEMPROPERTYNAME ) != null || AgentFileInstaller.class.getResource( VERSION_RESOURCE_NAME ) != null ; } private AgentFileInstaller() throws IOException { final String versionOverride = System.getProperty( VERSIONOVERRIDE_SYSTEMPROPERTYNAME ) ; if( versionOverride == null ) { final URL versionResource = AgentFileInstaller.class.getResource( VERSION_RESOURCE_NAME ) ; + if( versionResource == null ) { + throw new IllegalStateException( "Couldn't find resource for '" + VERSION_RESOURCE_NAME + "' " + + "(when building with Maven, this may be caused by Insider jar not present " + + "in the repository for current version)" + ) ; + } version = Resources.toString( versionResource, Charsets.UTF_8 ) ; LOGGER.info( "Using version '", version, "' as found inside ", "'", VERSION_RESOURCE_NAME, "' resource." ) ; } else { version = versionOverride ; LOGGER.info( "Using version override '", version, "' from system property ", "'", VERSIONOVERRIDE_SYSTEMPROPERTYNAME, "'." ) ; } final String jarFileNameFromSystemProperty = System.getProperty( AGENTJARFILE_SYSTEMPROPERTYNAME ) ; if( jarFileNameFromSystemProperty == null ) { try { jarFile = File.createTempFile( "Novelang-insider-agent", ".jar" ).getCanonicalFile() ; copyResourceToFile( JAR_RESOURCE_NAME_RADIX + version + ".jar", jarFile ) ; LOGGER.info( "Using jar file '", jarFile.getAbsolutePath(), "'." ) ; } catch( IOException e ) { throw new RuntimeException( e ) ; } } else { jarFile = resolveWithVersion( jarFileNameFromSystemProperty ) ; if( ! jarFile.isFile() ) { throw new IllegalArgumentException( "Jar file '" + jarFile.getAbsolutePath() + "' doesn't exist as a file" ) ; } LOGGER.info( "Using jar file '", jarFile.getAbsolutePath(), "' ", "set from system property '", AGENTJARFILE_SYSTEMPROPERTYNAME, "'." ) ; } } public File resolveWithVersion( final String filenameWithVersionPlaceholders ) { final String resolvedJarFileName = filenameWithVersionPlaceholders.replaceAll( VERSION_PLACEHOLDER_REGEX, version ) ; final File resolvedFile = new File( resolvedJarFileName ); return resolvedFile; } /** * Returns a {@code File} object referencing the jar containing the * {@link org.novelang.outfit.shell.insider.InsiderAgent}. * * @return a non-null object. */ public File getJarFile() { return jarFile ; } public void copyVersionedJarToFile( final String jarResourceRadix, final File file ) throws IOException { copyResourceToFile( jarResourceRadix + version + ".jar", file ) ; } public static void copyResourceToFile( final String resourceName, final File file ) throws IOException { final URL resourceUrl = AgentFileInstaller.class.getResource( resourceName ) ; if( resourceUrl == null ) { throw new MissingResourceException( "The resource '" + resourceName +"' does not appear in the classpath " + "(Maven should handle this, IDEs probably won't)", AgentFileInstaller.class.getName(), resourceName ) ; } LOGGER.info( "Copying resource '", resourceName, "' to ", "'", file.getAbsolutePath(), "'" ) ; FileUtils.copyURLToFile( resourceUrl, file ) ; } /** * Defined by the assembly of the Insider project. */ @SuppressWarnings( { "HardcodedFileSeparator" } ) private static final String JAR_RESOURCE_NAME_RADIX = "/org/novelang/outfit/shell/Novelang-insider-" ; /** * Defined by the assembly of the Insider project. */ @SuppressWarnings( { "HardcodedFileSeparator" } ) private static final String VERSION_RESOURCE_NAME= "/org/novelang/outfit/shell/version.txt" ; // ======================== // Initialization on demand // ======================== @SuppressWarnings( { "UtilityClassWithoutPrivateConstructor" } ) private static class LazyHolder { private static final AgentFileInstaller INSTANCE ; static { try { INSTANCE = new AgentFileInstaller() ; } catch( IOException e ) { throw new RuntimeException( e ) ; } } } public static AgentFileInstaller getInstance() { return LazyHolder.INSTANCE ; } }
true
true
private AgentFileInstaller() throws IOException { final String versionOverride = System.getProperty( VERSIONOVERRIDE_SYSTEMPROPERTYNAME ) ; if( versionOverride == null ) { final URL versionResource = AgentFileInstaller.class.getResource( VERSION_RESOURCE_NAME ) ; version = Resources.toString( versionResource, Charsets.UTF_8 ) ; LOGGER.info( "Using version '", version, "' as found inside ", "'", VERSION_RESOURCE_NAME, "' resource." ) ; } else { version = versionOverride ; LOGGER.info( "Using version override '", version, "' from system property ", "'", VERSIONOVERRIDE_SYSTEMPROPERTYNAME, "'." ) ; } final String jarFileNameFromSystemProperty = System.getProperty( AGENTJARFILE_SYSTEMPROPERTYNAME ) ; if( jarFileNameFromSystemProperty == null ) { try { jarFile = File.createTempFile( "Novelang-insider-agent", ".jar" ).getCanonicalFile() ; copyResourceToFile( JAR_RESOURCE_NAME_RADIX + version + ".jar", jarFile ) ; LOGGER.info( "Using jar file '", jarFile.getAbsolutePath(), "'." ) ; } catch( IOException e ) { throw new RuntimeException( e ) ; } } else { jarFile = resolveWithVersion( jarFileNameFromSystemProperty ) ; if( ! jarFile.isFile() ) { throw new IllegalArgumentException( "Jar file '" + jarFile.getAbsolutePath() + "' doesn't exist as a file" ) ; } LOGGER.info( "Using jar file '", jarFile.getAbsolutePath(), "' ", "set from system property '", AGENTJARFILE_SYSTEMPROPERTYNAME, "'." ) ; } }
private AgentFileInstaller() throws IOException { final String versionOverride = System.getProperty( VERSIONOVERRIDE_SYSTEMPROPERTYNAME ) ; if( versionOverride == null ) { final URL versionResource = AgentFileInstaller.class.getResource( VERSION_RESOURCE_NAME ) ; if( versionResource == null ) { throw new IllegalStateException( "Couldn't find resource for '" + VERSION_RESOURCE_NAME + "' " + "(when building with Maven, this may be caused by Insider jar not present " + "in the repository for current version)" ) ; } version = Resources.toString( versionResource, Charsets.UTF_8 ) ; LOGGER.info( "Using version '", version, "' as found inside ", "'", VERSION_RESOURCE_NAME, "' resource." ) ; } else { version = versionOverride ; LOGGER.info( "Using version override '", version, "' from system property ", "'", VERSIONOVERRIDE_SYSTEMPROPERTYNAME, "'." ) ; } final String jarFileNameFromSystemProperty = System.getProperty( AGENTJARFILE_SYSTEMPROPERTYNAME ) ; if( jarFileNameFromSystemProperty == null ) { try { jarFile = File.createTempFile( "Novelang-insider-agent", ".jar" ).getCanonicalFile() ; copyResourceToFile( JAR_RESOURCE_NAME_RADIX + version + ".jar", jarFile ) ; LOGGER.info( "Using jar file '", jarFile.getAbsolutePath(), "'." ) ; } catch( IOException e ) { throw new RuntimeException( e ) ; } } else { jarFile = resolveWithVersion( jarFileNameFromSystemProperty ) ; if( ! jarFile.isFile() ) { throw new IllegalArgumentException( "Jar file '" + jarFile.getAbsolutePath() + "' doesn't exist as a file" ) ; } LOGGER.info( "Using jar file '", jarFile.getAbsolutePath(), "' ", "set from system property '", AGENTJARFILE_SYSTEMPROPERTYNAME, "'." ) ; } }
diff --git a/disambiguation-work/src/main/java/pl/edu/icm/coansys/disambiguation/work/DuplicateWorkDetectReduceService.java b/disambiguation-work/src/main/java/pl/edu/icm/coansys/disambiguation/work/DuplicateWorkDetectReduceService.java index 7d98dda6..30843c10 100644 --- a/disambiguation-work/src/main/java/pl/edu/icm/coansys/disambiguation/work/DuplicateWorkDetectReduceService.java +++ b/disambiguation-work/src/main/java/pl/edu/icm/coansys/disambiguation/work/DuplicateWorkDetectReduceService.java @@ -1,141 +1,142 @@ package pl.edu.icm.coansys.disambiguation.work; import java.io.IOException; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pl.edu.icm.coansys.commons.spring.DiReduceService; import pl.edu.icm.coansys.models.DocumentProtos.DocumentWrapper; import com.google.common.collect.Lists; import com.google.common.collect.Maps; /** * * @author Łukasz Dumiszewski * */ @Service("duplicateWorkDetectReduceService") public class DuplicateWorkDetectReduceService implements DiReduceService<Text, BytesWritable, Text, BytesWritable> { //@SuppressWarnings("unused") private static Logger log = LoggerFactory.getLogger(DuplicateWorkDetectReduceService.class); @Autowired private DuplicateWorkService duplicateWorkService; //******************** DiReduceService Implementation ******************** @Override public void reduce(Text key, Iterable<BytesWritable> values, Reducer<Text, BytesWritable, Text, BytesWritable>.Context context) throws IOException, InterruptedException { List<DocumentWrapper> documents = DocumentWrapperUtils.extractDocumentWrappers(key, values); long startTime = new Date().getTime(); process(key, context, documents, 0, 1000); log.info("time [msec]: " + (new Date().getTime()-startTime)); } //******************** PRIVATE ******************** /** * Processes the given documents: finds duplicates and saves them to the context under the same, common key. * If the number of the passed documents is greater than the <b>maxNumberOfDocuments</b> then the documents are split into smaller parts and * then the method is recursively invoked for each one of those parts. * @param key a common key of the documents * @param level the recursive depth of the method used to generate a proper key of the passed documents. The greater the level the longer (and more unique) the * generated key. */ void process(Text key, Reducer<Text, BytesWritable, Text, BytesWritable>.Context context, List<DocumentWrapper> documents, int level, int maxNumberOfDocuments) throws IOException, InterruptedException { String dashes = getDashes(level); log.info(dashes+ "start process, key: {}, number of documents: {}", key.toString(), documents.size()); if (documents.size()<2) { log.info(dashes+ "one document only, ommiting"); return; } int lev = level + 1; + int maxNumOfDocs = maxNumberOfDocuments; - if (documents.size()>maxNumberOfDocuments) { + if (documents.size()>maxNumOfDocs) { Map<Text, List<DocumentWrapper>> documentPacks = splitDocuments(key, documents, lev); log.info(dashes+ "documents split into: {} packs", documentPacks.size()); for (Map.Entry<Text, List<DocumentWrapper>> docs : documentPacks.entrySet()) { if (docs.getValue().size()==documents.size()) { // docs were not splitted, the generated key is the same for all the titles, may happen if the documents have the same short title, e.g. news in brief - maxNumberOfDocuments+=maxNumberOfDocuments; + maxNumOfDocs+=maxNumOfDocs; } - process(docs.getKey(), context, docs.getValue(), lev, maxNumberOfDocuments); + process(docs.getKey(), context, docs.getValue(), lev, maxNumOfDocs); } } else { Map<Integer, Set<DocumentWrapper>> duplicateWorksMap = duplicateWorkService.findDuplicates(documents); saveDuplicatesToContext(duplicateWorksMap, key, context); context.progress(); } log.info(dashes+ "end process, key: {}", key); } private String getDashes(int level) { StringBuilder sb = new StringBuilder(); for (int i=0; i<=level; i++) { sb.append("-"); } return sb.toString(); } /** * Splits the passed documents into smaller parts. The documents are divided into smaller packs according to the generated keys. * The keys are generated by using the {@link WorkKeyGenerator.generateKey(doc, level)} method. */ Map<Text, List<DocumentWrapper>> splitDocuments(Text key, List<DocumentWrapper> documents, int level) { Map<Text, List<DocumentWrapper>> splitDocuments = Maps.newHashMap(); for (DocumentWrapper doc : documents) { Text newKey = new Text(WorkKeyGenerator.generateKey(doc, level)); List<DocumentWrapper> list = splitDocuments.get(newKey); if (list == null) { list = Lists.newArrayList(); splitDocuments.put(newKey, list); } list.add(doc); } return splitDocuments; } private void saveDuplicatesToContext(Map<Integer, Set<DocumentWrapper>> sameWorksMap, Text key, Reducer<Text, BytesWritable, Text, BytesWritable>.Context context) throws IOException, InterruptedException { for (Map.Entry<Integer, Set<DocumentWrapper>> entry : sameWorksMap.entrySet()) { String sameWorksKey = key.toString() + "_" + entry.getKey(); for (DocumentWrapper doc : entry.getValue()) { context.write(new Text(sameWorksKey), new BytesWritable(doc.toByteArray())); } } } }
false
true
void process(Text key, Reducer<Text, BytesWritable, Text, BytesWritable>.Context context, List<DocumentWrapper> documents, int level, int maxNumberOfDocuments) throws IOException, InterruptedException { String dashes = getDashes(level); log.info(dashes+ "start process, key: {}, number of documents: {}", key.toString(), documents.size()); if (documents.size()<2) { log.info(dashes+ "one document only, ommiting"); return; } int lev = level + 1; if (documents.size()>maxNumberOfDocuments) { Map<Text, List<DocumentWrapper>> documentPacks = splitDocuments(key, documents, lev); log.info(dashes+ "documents split into: {} packs", documentPacks.size()); for (Map.Entry<Text, List<DocumentWrapper>> docs : documentPacks.entrySet()) { if (docs.getValue().size()==documents.size()) { // docs were not splitted, the generated key is the same for all the titles, may happen if the documents have the same short title, e.g. news in brief maxNumberOfDocuments+=maxNumberOfDocuments; } process(docs.getKey(), context, docs.getValue(), lev, maxNumberOfDocuments); } } else { Map<Integer, Set<DocumentWrapper>> duplicateWorksMap = duplicateWorkService.findDuplicates(documents); saveDuplicatesToContext(duplicateWorksMap, key, context); context.progress(); } log.info(dashes+ "end process, key: {}", key); }
void process(Text key, Reducer<Text, BytesWritable, Text, BytesWritable>.Context context, List<DocumentWrapper> documents, int level, int maxNumberOfDocuments) throws IOException, InterruptedException { String dashes = getDashes(level); log.info(dashes+ "start process, key: {}, number of documents: {}", key.toString(), documents.size()); if (documents.size()<2) { log.info(dashes+ "one document only, ommiting"); return; } int lev = level + 1; int maxNumOfDocs = maxNumberOfDocuments; if (documents.size()>maxNumOfDocs) { Map<Text, List<DocumentWrapper>> documentPacks = splitDocuments(key, documents, lev); log.info(dashes+ "documents split into: {} packs", documentPacks.size()); for (Map.Entry<Text, List<DocumentWrapper>> docs : documentPacks.entrySet()) { if (docs.getValue().size()==documents.size()) { // docs were not splitted, the generated key is the same for all the titles, may happen if the documents have the same short title, e.g. news in brief maxNumOfDocs+=maxNumOfDocs; } process(docs.getKey(), context, docs.getValue(), lev, maxNumOfDocs); } } else { Map<Integer, Set<DocumentWrapper>> duplicateWorksMap = duplicateWorkService.findDuplicates(documents); saveDuplicatesToContext(duplicateWorksMap, key, context); context.progress(); } log.info(dashes+ "end process, key: {}", key); }
diff --git a/src/main/java/hudson/plugins/collabnet/auth/CNAuthentication.java b/src/main/java/hudson/plugins/collabnet/auth/CNAuthentication.java index 65149f7..a426062 100644 --- a/src/main/java/hudson/plugins/collabnet/auth/CNAuthentication.java +++ b/src/main/java/hudson/plugins/collabnet/auth/CNAuthentication.java @@ -1,218 +1,220 @@ package hudson.plugins.collabnet.auth; import com.collabnet.ce.webservices.CTFProject; import com.collabnet.ce.webservices.CTFUser; import com.collabnet.ce.webservices.CollabNetApp; import hudson.model.Hudson; import hudson.security.Permission; import org.acegisecurity.Authentication; import org.acegisecurity.GrantedAuthority; import org.acegisecurity.GrantedAuthorityImpl; import java.rmi.RemoteException; import java.util.Collection; import java.util.Collections; import java.util.Set; import java.util.logging.Logger; /** * Authentication class for CollabNet. */ public class CNAuthentication implements Authentication { public static final String SUPER_USER = "SuperUser"; private final String principal; private final CTFUser myself; private final CollabNetApp cna; private GrantedAuthority[] authorities; private Collection<String> groups; private boolean authenticated = false; private boolean cnauthed = false; private CNAuthorizationCache mAuthCache = null; private static Logger log = Logger.getLogger("CNAuthentication"); public CNAuthentication(Object principal, Object credentials) throws RemoteException { this.principal = (String) principal; this.cna = (CollabNetApp) credentials; this.myself = cna.getMyself(); this.setupAuthorities(); this.setupGroups(); this.setAuthenticated(true); mAuthCache = new CNAuthorizationCache(); } /** * The only granted authority is superuser-ness. */ private void setupAuthorities() { boolean isSuper = false; try { isSuper = myself.isSuperUser(); } catch (RemoteException re) { log.info("setupAuthoritites: failed with RemoteException: " + re.getMessage()); } if (isSuper) { - this.authorities = new GrantedAuthority[1]; + this.authorities = new GrantedAuthority[2]; this.authorities[0] = new GrantedAuthorityImpl(CNAuthentication.SUPER_USER); + this.authorities[1] = new GrantedAuthorityImpl("authenticated"); } else { - this.authorities = new GrantedAuthority[0]; + this.authorities = new GrantedAuthority[1]; + this.authorities[0] = new GrantedAuthorityImpl("authenticated"); } } /** * Check which groups this user belongs to. */ private void setupGroups() { this.groups = Collections.emptyList(); try { this.groups = myself.getGroupNames(); } catch (RemoteException re) { // not much we can do } } public void setAuthenticated(boolean authenticated) { this.authenticated = authenticated; } public boolean isAuthenticated() { return this.authenticated; } /** * @return a copy of the granted authorities. */ public GrantedAuthority[] getAuthorities() { GrantedAuthority[] authCopy = new GrantedAuthority[this.authorities.length]; System.arraycopy(this.authorities, 0, authCopy, 0, this.authorities.length); return authCopy; } public String getPrincipal() { return this.principal; } public String getName() { return this.getPrincipal(); } public Object getDetails() { return null; } public CollabNetApp getCredentials() { return this.cna; } /** * @param group name of a CN group. * @return true if the user is a member of the given group. */ public boolean isMember(String group) { return this.groups.contains(group); } public String toString() { return "CNAuthentication [for: " + this.getPrincipal() + ", authenticated=" + this.isAuthenticated() + "]"; } /** * Determine whether we have authenticated to CTF in the browser. * @return true if authenticated */ public boolean isCNAuthed() { return this.cnauthed; } /** * Set whether we have authenticated to CTF in the browser. * @param cnauthed true if current session is CTF authenticated in browser */ public void setCNAuthed(boolean cnauthed) { this.cnauthed = cnauthed; } /** * Determines if the authenticated user is a super user. * This is currently from data that's calculated once (on login). * If this ever turns out to be insufficient, we could change this * method to get the data on the fly. */ public boolean isSuperUser() { for (GrantedAuthority authority: getAuthorities()) { if (authority.getAuthority().equals(CNAuthentication.SUPER_USER)) { return true; } } return false; } /** * Determines if the authenticated user belongs to any of the groups. * This is currently from data that's calculated once (on login). * If this ever turns out to be insufficient, we could change this * method to get the data on the fly. * * @param groups * @return true if the user is a member of any of the groups. */ public boolean isMemberOfAny(Collection<String> groups) { for (String group: groups) { if (this.isMember(group)) { return true; } } return false; } /** * Determines if the authenticated user is a project admin. * * @return true if the user is a project admin. */ public boolean isProjectAdmin(CTFProject p) { try { return p.getAdmins().contains(cna.getMyself()); } catch (RemoteException re) { log.info("isProjectAdmin: failed with RemoteException: " + re.getMessage()); return false; } } public String getSessionId() { return this.getCredentials().getSessionId(); } /** * Get a set of all permission that a user has for a given project. * @param username user name * @param projectId project id * @return set of permissions */ public Set<Permission> getUserProjectPermSet(String username, String projectId) { return mAuthCache.getUserProjectPermSet(username, projectId); } /** * If the current thread carries the {@link CNAuthentication} object as the context, * returns it. Or else null. */ public static CNAuthentication get() { return cast(Hudson.getAuthentication()); } public static CNAuthentication cast(Authentication a) { if (a instanceof CNAuthentication) { return (CNAuthentication) a; } else { return null; } } }
false
true
private void setupAuthorities() { boolean isSuper = false; try { isSuper = myself.isSuperUser(); } catch (RemoteException re) { log.info("setupAuthoritites: failed with RemoteException: " + re.getMessage()); } if (isSuper) { this.authorities = new GrantedAuthority[1]; this.authorities[0] = new GrantedAuthorityImpl(CNAuthentication.SUPER_USER); } else { this.authorities = new GrantedAuthority[0]; } }
private void setupAuthorities() { boolean isSuper = false; try { isSuper = myself.isSuperUser(); } catch (RemoteException re) { log.info("setupAuthoritites: failed with RemoteException: " + re.getMessage()); } if (isSuper) { this.authorities = new GrantedAuthority[2]; this.authorities[0] = new GrantedAuthorityImpl(CNAuthentication.SUPER_USER); this.authorities[1] = new GrantedAuthorityImpl("authenticated"); } else { this.authorities = new GrantedAuthority[1]; this.authorities[0] = new GrantedAuthorityImpl("authenticated"); } }
diff --git a/src/network/Communicator.java b/src/network/Communicator.java index 398ba94..56aa776 100644 --- a/src/network/Communicator.java +++ b/src/network/Communicator.java @@ -1,167 +1,167 @@ package network; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.NotYetConnectedException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; import app.Mediator; /** * Class used to communicate with the server and other clients */ public class Communicator { SocketChannel chan = null; Selector selector; Mediator m; public Communicator(Mediator m) { this.m = m; } public void read(final SelectionKey key) throws Exception { DataContainer data = (DataContainer)key.attachment(); SocketChannel socket = (SocketChannel)key.channel(); System.out.println("READ"); int bytesRead = 0; try { while (data.lengthByteBuffer.remaining()!=0) { bytesRead = socket.read(data.lengthByteBuffer); if (bytesRead < 0 ) { m.loginError("Connection failure"); key.channel().close(); return; } } data.dataByteBuffer = ByteBuffer.allocate(data.lengthByteBuffer.getInt(0)); data.lengthByteBuffer.clear(); while (data.dataByteBuffer.remaining()!=0) { bytesRead = socket.read(data.dataByteBuffer); if (bytesRead < 0 ) { m.loginError("Connection failure"); key.channel().close(); return; } } System.out.println(data.dataByteBuffer); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data.dataByteBuffer.array())); Serializable ret = (Serializable) ois.readObject(); // clean up data.dataByteBuffer = null; data.readLength = true; System.out.println("RESULT "+ret); ((S2CMessage)ret).execute(m); } catch (NotYetConnectedException e) { } catch (IOException e) { System.err.println("Disconnect: "+e); m.loginError("Connection failure"); key.channel().close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("READ done"); } public boolean connect(String IP, int PORT) { try { chan = SocketChannel.open(); chan.configureBlocking(false); selector = Selector.open(); chan.register(selector, SelectionKey.OP_READ, new DataContainer()); } catch (Exception e) { System.err.println("SocketChannel Failed"); return false; } try { chan.connect(new InetSocketAddress(IP, PORT)); - chan.finishConnect(); + while(!chan.finishConnect()); // wait for connection to complete Thread t = new Thread() { public void run() { while (true) { try { selector.select(); for (Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it.hasNext(); ) { System.out.println("Event"); SelectionKey key = it.next(); it.remove(); if (key.isReadable()) read(key); } } catch (NotYetConnectedException e) { System.out.println("Not Yet Connected so do nothing"); } catch (Exception e) { e.printStackTrace(); } } } }; t.start(); return true; } catch (Exception e) { System.err.println("Connection failed: "+e); m.loginError("Connection failed"); return false; } } public void send(Serializable obj) { try { ByteArrayOutputStream bs = new ByteArrayOutputStream(); for(int i=0;i<4;i++) bs.write(0); ObjectOutputStream os = new ObjectOutputStream(bs); os.writeObject(obj); os.close(); ByteBuffer wrap = ByteBuffer.wrap(bs.toByteArray()); wrap.putInt(0, bs.size()-4); int bytesOut = 0; while (bytesOut<bs.size()) { int out = chan.write(wrap); if (out<0) { System.err.println("CLOSED"); chan.close(); } bytesOut += out; } } catch (Exception e) { System.err.println("Send Failed: "+e); m.loginError("Connection failure"); try { chan.close(); } catch (IOException e1) { System.err.println("WTF"); } } } } class DataContainer { ByteBuffer buf = null; ByteBuffer lengthByteBuffer = ByteBuffer.wrap(new byte[4]); boolean readLength = true; ByteBuffer dataByteBuffer = null; }
true
true
public boolean connect(String IP, int PORT) { try { chan = SocketChannel.open(); chan.configureBlocking(false); selector = Selector.open(); chan.register(selector, SelectionKey.OP_READ, new DataContainer()); } catch (Exception e) { System.err.println("SocketChannel Failed"); return false; } try { chan.connect(new InetSocketAddress(IP, PORT)); chan.finishConnect(); Thread t = new Thread() { public void run() { while (true) { try { selector.select(); for (Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it.hasNext(); ) { System.out.println("Event"); SelectionKey key = it.next(); it.remove(); if (key.isReadable()) read(key); } } catch (NotYetConnectedException e) { System.out.println("Not Yet Connected so do nothing"); } catch (Exception e) { e.printStackTrace(); } } } }; t.start(); return true; } catch (Exception e) { System.err.println("Connection failed: "+e); m.loginError("Connection failed"); return false; } }
public boolean connect(String IP, int PORT) { try { chan = SocketChannel.open(); chan.configureBlocking(false); selector = Selector.open(); chan.register(selector, SelectionKey.OP_READ, new DataContainer()); } catch (Exception e) { System.err.println("SocketChannel Failed"); return false; } try { chan.connect(new InetSocketAddress(IP, PORT)); while(!chan.finishConnect()); // wait for connection to complete Thread t = new Thread() { public void run() { while (true) { try { selector.select(); for (Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it.hasNext(); ) { System.out.println("Event"); SelectionKey key = it.next(); it.remove(); if (key.isReadable()) read(key); } } catch (NotYetConnectedException e) { System.out.println("Not Yet Connected so do nothing"); } catch (Exception e) { e.printStackTrace(); } } } }; t.start(); return true; } catch (Exception e) { System.err.println("Connection failed: "+e); m.loginError("Connection failed"); return false; } }
diff --git a/src/org/intellij/erlang/runner/ErlangRunningState.java b/src/org/intellij/erlang/runner/ErlangRunningState.java index 51162a67..4efdab6e 100644 --- a/src/org/intellij/erlang/runner/ErlangRunningState.java +++ b/src/org/intellij/erlang/runner/ErlangRunningState.java @@ -1,61 +1,62 @@ package org.intellij.erlang.runner; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.CommandLineState; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.filters.TextConsoleBuilder; import com.intellij.execution.filters.TextConsoleBuilderFactory; import com.intellij.execution.process.OSProcessHandler; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.compiler.CompilerPaths; import com.intellij.openapi.module.Module; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import org.intellij.erlang.sdk.ErlangSdkType; import org.jetbrains.annotations.NotNull; /** * @author ignatov */ public class ErlangRunningState extends CommandLineState { private final Module module; private final ErlangApplicationConfiguration myConfiguration; public ErlangRunningState(ExecutionEnvironment env, Module module, ErlangApplicationConfiguration configuration) { super(env); this.module = module; myConfiguration = configuration; } @NotNull @Override protected ProcessHandler startProcess() throws ExecutionException { final Sdk sdk = ModuleRootManager.getInstance(module).getSdk(); assert sdk != null; GeneralCommandLine commandLine = getCommand(sdk); return new OSProcessHandler(commandLine.createProcess(), commandLine.getCommandLineString()); } private GeneralCommandLine getCommand(Sdk sdk) throws ExecutionException { final GeneralCommandLine commandLine = new GeneralCommandLine(); VirtualFile moduleOutputDirectory = CompilerPaths.getModuleOutputDirectory(module, false); String erl = FileUtil.toSystemDependentName(ErlangSdkType.getTopLevelExecutable(sdk.getHomePath()).getAbsolutePath()); String canonicalPath = moduleOutputDirectory.getCanonicalPath(); commandLine.setWorkDirectory(canonicalPath); commandLine.setExePath(erl); - commandLine.addParameters("-s", "init", "stop", "-noshell", "-run"); + commandLine.addParameters("-run"); commandLine.addParameters(StringUtil.split(myConfiguration.getModuleAndFunction(), " ")); commandLine.addParameters(StringUtil.split(myConfiguration.getParams(), " ")); + commandLine.addParameters("-s", "init", "stop", "-noshell"); final TextConsoleBuilder consoleBuilder = TextConsoleBuilderFactory.getInstance().createBuilder(module.getProject()); setConsoleBuilder(consoleBuilder); return commandLine; } }
false
true
private GeneralCommandLine getCommand(Sdk sdk) throws ExecutionException { final GeneralCommandLine commandLine = new GeneralCommandLine(); VirtualFile moduleOutputDirectory = CompilerPaths.getModuleOutputDirectory(module, false); String erl = FileUtil.toSystemDependentName(ErlangSdkType.getTopLevelExecutable(sdk.getHomePath()).getAbsolutePath()); String canonicalPath = moduleOutputDirectory.getCanonicalPath(); commandLine.setWorkDirectory(canonicalPath); commandLine.setExePath(erl); commandLine.addParameters("-s", "init", "stop", "-noshell", "-run"); commandLine.addParameters(StringUtil.split(myConfiguration.getModuleAndFunction(), " ")); commandLine.addParameters(StringUtil.split(myConfiguration.getParams(), " ")); final TextConsoleBuilder consoleBuilder = TextConsoleBuilderFactory.getInstance().createBuilder(module.getProject()); setConsoleBuilder(consoleBuilder); return commandLine; }
private GeneralCommandLine getCommand(Sdk sdk) throws ExecutionException { final GeneralCommandLine commandLine = new GeneralCommandLine(); VirtualFile moduleOutputDirectory = CompilerPaths.getModuleOutputDirectory(module, false); String erl = FileUtil.toSystemDependentName(ErlangSdkType.getTopLevelExecutable(sdk.getHomePath()).getAbsolutePath()); String canonicalPath = moduleOutputDirectory.getCanonicalPath(); commandLine.setWorkDirectory(canonicalPath); commandLine.setExePath(erl); commandLine.addParameters("-run"); commandLine.addParameters(StringUtil.split(myConfiguration.getModuleAndFunction(), " ")); commandLine.addParameters(StringUtil.split(myConfiguration.getParams(), " ")); commandLine.addParameters("-s", "init", "stop", "-noshell"); final TextConsoleBuilder consoleBuilder = TextConsoleBuilderFactory.getInstance().createBuilder(module.getProject()); setConsoleBuilder(consoleBuilder); return commandLine; }
diff --git a/src/main/java/dal/admin/ImageStore.java b/src/main/java/dal/admin/ImageStore.java index b59cb74..51779be 100644 --- a/src/main/java/dal/admin/ImageStore.java +++ b/src/main/java/dal/admin/ImageStore.java @@ -1,73 +1,73 @@ package dal.admin; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; /** * * This class is responsible for inserting and retrieving * images from our database * @author Stian Sandve * */ public class ImageStore implements IImageStore { protected Connection conn; public ImageStore(Connection conn) { this.conn = conn; } public synchronized boolean insert(Image img) { try { PreparedStatement statement = conn.prepareStatement( "INSERT INTO images " + " (url, external_id, description, created_time)" + " VALUES (?, ?, ?, ?);"); statement.setString(1, img.getUrl()); statement.setLong(2, img.getID()); statement.setString(3, img.getDescription()); statement.setDate(4, img.getCreatedTime()); return statement.executeUpdate() == 1; } catch (SQLException e) { e.printStackTrace(); return false; } } public synchronized ArrayList<Image> getLast(int numberOfRows) { if(numberOfRows < 0) { throw new IllegalArgumentException(); } ArrayList<Image> images = new ArrayList<Image>(); try { PreparedStatement statement = conn.prepareStatement( - "SELECT id, url, external_id, description, created_time "+ - "WHERE blocked='0'"+ - " FROM images ORDER BY id DESC LIMIT ?;"); + "SELECT id, url, external_id, description, created_time" + + " FROM images WHERE blocked='0'"+ + " ORDER BY id DESC LIMIT ?;"); statement.setInt(1, numberOfRows); ResultSet result = statement.executeQuery(); while (result.next()) { Image img = new Image( result.getString("url"), result.getLong("external_id"), result.getString("description"), result.getDate("created_time") ); img.setInternalId(result.getInt("id")); images.add(img); } } catch (SQLException e) { e.printStackTrace(); } return images; } }
true
true
public synchronized ArrayList<Image> getLast(int numberOfRows) { if(numberOfRows < 0) { throw new IllegalArgumentException(); } ArrayList<Image> images = new ArrayList<Image>(); try { PreparedStatement statement = conn.prepareStatement( "SELECT id, url, external_id, description, created_time "+ "WHERE blocked='0'"+ " FROM images ORDER BY id DESC LIMIT ?;"); statement.setInt(1, numberOfRows); ResultSet result = statement.executeQuery(); while (result.next()) { Image img = new Image( result.getString("url"), result.getLong("external_id"), result.getString("description"), result.getDate("created_time") ); img.setInternalId(result.getInt("id")); images.add(img); } } catch (SQLException e) { e.printStackTrace(); } return images; }
public synchronized ArrayList<Image> getLast(int numberOfRows) { if(numberOfRows < 0) { throw new IllegalArgumentException(); } ArrayList<Image> images = new ArrayList<Image>(); try { PreparedStatement statement = conn.prepareStatement( "SELECT id, url, external_id, description, created_time" + " FROM images WHERE blocked='0'"+ " ORDER BY id DESC LIMIT ?;"); statement.setInt(1, numberOfRows); ResultSet result = statement.executeQuery(); while (result.next()) { Image img = new Image( result.getString("url"), result.getLong("external_id"), result.getString("description"), result.getDate("created_time") ); img.setInternalId(result.getInt("id")); images.add(img); } } catch (SQLException e) { e.printStackTrace(); } return images; }
diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPicture.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPicture.java index 66a6d9c5a..728a8dd93 100644 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPicture.java +++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPicture.java @@ -1,323 +1,323 @@ /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.xssf.usermodel; import java.awt.Dimension; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import org.apache.poi.POIXMLDocumentPart; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.ss.usermodel.Picture; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.ImageUtils; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; import org.apache.poi.util.Internal; import org.openxmlformats.schemas.drawingml.x2006.main.CTBlipFillProperties; import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualPictureProperties; import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D; import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetGeometry2D; import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D; import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType; import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTPicture; import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTPictureNonVisual; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * Represents a picture shape in a SpreadsheetML drawing. * * @author Yegor Kozlov */ public final class XSSFPicture extends XSSFShape implements Picture { private static final POILogger logger = POILogFactory.getLogger(XSSFPicture.class); /** * Column width measured as the number of characters of the maximum digit width of the * numbers 0, 1, 2, ..., 9 as rendered in the normal style's font. There are 4 pixels of margin * padding (two on each side), plus 1 pixel padding for the gridlines. * * This value is the same for default font in Office 2007 (Calibry) and Office 2003 and earlier (Arial) */ private static float DEFAULT_COLUMN_WIDTH = 9.140625f; /** * A default instance of CTShape used for creating new shapes. */ private static CTPicture prototype = null; /** * This object specifies a picture object and all its properties */ private CTPicture ctPicture; /** * Construct a new XSSFPicture object. This constructor is called from * {@link XSSFDrawing#createPicture(XSSFClientAnchor, int)} * * @param drawing the XSSFDrawing that owns this picture */ protected XSSFPicture(XSSFDrawing drawing, CTPicture ctPicture){ this.drawing = drawing; this.ctPicture = ctPicture; } /** * Returns a prototype that is used to construct new shapes * * @return a prototype that is used to construct new shapes */ protected static CTPicture prototype(){ if(prototype == null) { CTPicture pic = CTPicture.Factory.newInstance(); CTPictureNonVisual nvpr = pic.addNewNvPicPr(); CTNonVisualDrawingProps nvProps = nvpr.addNewCNvPr(); nvProps.setId(1); nvProps.setName("Picture 1"); nvProps.setDescr("Picture"); CTNonVisualPictureProperties nvPicProps = nvpr.addNewCNvPicPr(); nvPicProps.addNewPicLocks().setNoChangeAspect(true); CTBlipFillProperties blip = pic.addNewBlipFill(); blip.addNewBlip().setEmbed(""); blip.addNewStretch().addNewFillRect(); CTShapeProperties sppr = pic.addNewSpPr(); CTTransform2D t2d = sppr.addNewXfrm(); CTPositiveSize2D ext = t2d.addNewExt(); //should be original picture width and height expressed in EMUs ext.setCx(0); ext.setCy(0); CTPoint2D off = t2d.addNewOff(); off.setX(0); off.setY(0); CTPresetGeometry2D prstGeom = sppr.addNewPrstGeom(); prstGeom.setPrst(STShapeType.RECT); prstGeom.addNewAvLst(); prototype = pic; } return prototype; } /** * Link this shape with the picture data * * @param rel relationship referring the picture data */ protected void setPictureReference(PackageRelationship rel){ ctPicture.getBlipFill().getBlip().setEmbed(rel.getId()); } /** * Return the underlying CTPicture bean that holds all properties for this picture * * @return the underlying CTPicture bean */ @Internal public CTPicture getCTPicture(){ return ctPicture; } /** * Reset the image to the original size. * * <p> * Please note, that this method works correctly only for workbooks * with the default font size (Calibri 11pt for .xlsx). * If the default font is changed the resized image can be streched vertically or horizontally. * </p> */ public void resize(){ resize(1.0); } /** * Reset the image to the original size. * <p> * Please note, that this method works correctly only for workbooks * with the default font size (Calibri 11pt for .xlsx). * If the default font is changed the resized image can be streched vertically or horizontally. * </p> * * @param scale the amount by which image dimensions are multiplied relative to the original size. * <code>resize(1.0)</code> sets the original size, <code>resize(0.5)</code> resize to 50% of the original, * <code>resize(2.0)</code> resizes to 200% of the original. */ public void resize(double scale){ XSSFClientAnchor anchor = (XSSFClientAnchor)getAnchor(); XSSFClientAnchor pref = getPreferredSize(scale); int row2 = anchor.getRow1() + (pref.getRow2() - pref.getRow1()); int col2 = anchor.getCol1() + (pref.getCol2() - pref.getCol1()); anchor.setCol2(col2); anchor.setDx1(0); anchor.setDx2(pref.getDx2()); anchor.setRow2(row2); anchor.setDy1(0); anchor.setDy2(pref.getDy2()); } /** * Calculate the preferred size for this picture. * * @return XSSFClientAnchor with the preferred size for this image */ public XSSFClientAnchor getPreferredSize(){ return getPreferredSize(1); } /** * Calculate the preferred size for this picture. * * @param scale the amount by which image dimensions are multiplied relative to the original size. * @return XSSFClientAnchor with the preferred size for this image */ public XSSFClientAnchor getPreferredSize(double scale){ XSSFClientAnchor anchor = (XSSFClientAnchor)getAnchor(); XSSFPictureData data = getPictureData(); Dimension size = getImageDimension(data.getPackagePart(), data.getPictureType()); double scaledWidth = size.getWidth() * scale; double scaledHeight = size.getHeight() * scale; float w = 0; int col2 = anchor.getCol1(); int dx2 = 0; if(anchor.getDx1() > 0){ w += getColumnWidthInPixels(col2) - anchor.getDx1(); col2++; } for (;;) { w += getColumnWidthInPixels(col2); if(w > scaledWidth) break; col2++; } if(w > scaledWidth) { double cw = getColumnWidthInPixels(col2 + 1); double delta = w - scaledWidth; dx2 = (int)(EMU_PER_PIXEL*(cw-delta)); } anchor.setCol2(col2); anchor.setDx2(dx2); double h = 0; int row2 = anchor.getRow1(); int dy2 = 0; if(anchor.getDy1() > 0){ - h += getRowHeightInPixels(row2) - anchor.getDy1(); + h += getRowHeightInPixels(row2) - anchor.getDy1()/EMU_PER_PIXEL; row2++; } for (;;) { h += getRowHeightInPixels(row2); if(h > scaledHeight) break; row2++; } if(h > scaledHeight) { - double ch = getRowHeightInPixels(row2 + 1); + double ch = getRowHeightInPixels(row2); double delta = h - scaledHeight; dy2 = (int)(EMU_PER_PIXEL*(ch-delta)); } anchor.setRow2(row2); anchor.setDy2(dy2); CTPositiveSize2D size2d = ctPicture.getSpPr().getXfrm().getExt(); size2d.setCx((long)(scaledWidth*EMU_PER_PIXEL)); size2d.setCy((long)(scaledHeight*EMU_PER_PIXEL)); return anchor; } private float getColumnWidthInPixels(int columnIndex){ XSSFSheet sheet = (XSSFSheet)getDrawing().getParent(); CTCol col = sheet.getColumnHelper().getColumn(columnIndex, false); double numChars = col == null || !col.isSetWidth() ? DEFAULT_COLUMN_WIDTH : col.getWidth(); return (float)numChars*XSSFWorkbook.DEFAULT_CHARACTER_WIDTH; } private float getRowHeightInPixels(int rowIndex){ XSSFSheet sheet = (XSSFSheet)getDrawing().getParent(); XSSFRow row = sheet.getRow(rowIndex); float height = row != null ? row.getHeightInPoints() : sheet.getDefaultRowHeightInPoints(); return height*PIXEL_DPI/POINT_DPI; } /** * Return the dimension of this image * * @param part the package part holding raw picture data * @param type type of the picture: {@link Workbook#PICTURE_TYPE_JPEG}, * {@link Workbook#PICTURE_TYPE_PNG} or {@link Workbook#PICTURE_TYPE_DIB} * * @return image dimension in pixels */ protected static Dimension getImageDimension(PackagePart part, int type){ try { return ImageUtils.getImageDimension(part.getInputStream(), type); } catch (IOException e){ //return a "singulariry" if ImageIO failed to read the image logger.log(POILogger.WARN, e); return new Dimension(); } } /** * Return picture data for this shape * * @return picture data for this shape */ public XSSFPictureData getPictureData() { String blipId = ctPicture.getBlipFill().getBlip().getEmbed(); for (POIXMLDocumentPart part : getDrawing().getRelations()) { if(part.getPackageRelationship().getId().equals(blipId)){ return (XSSFPictureData)part; } } logger.log(POILogger.WARN, "Picture data was not found for blipId=" + blipId); return null; } protected CTShapeProperties getShapeProperties(){ return ctPicture.getSpPr(); } }
false
true
public XSSFClientAnchor getPreferredSize(double scale){ XSSFClientAnchor anchor = (XSSFClientAnchor)getAnchor(); XSSFPictureData data = getPictureData(); Dimension size = getImageDimension(data.getPackagePart(), data.getPictureType()); double scaledWidth = size.getWidth() * scale; double scaledHeight = size.getHeight() * scale; float w = 0; int col2 = anchor.getCol1(); int dx2 = 0; if(anchor.getDx1() > 0){ w += getColumnWidthInPixels(col2) - anchor.getDx1(); col2++; } for (;;) { w += getColumnWidthInPixels(col2); if(w > scaledWidth) break; col2++; } if(w > scaledWidth) { double cw = getColumnWidthInPixels(col2 + 1); double delta = w - scaledWidth; dx2 = (int)(EMU_PER_PIXEL*(cw-delta)); } anchor.setCol2(col2); anchor.setDx2(dx2); double h = 0; int row2 = anchor.getRow1(); int dy2 = 0; if(anchor.getDy1() > 0){ h += getRowHeightInPixels(row2) - anchor.getDy1(); row2++; } for (;;) { h += getRowHeightInPixels(row2); if(h > scaledHeight) break; row2++; } if(h > scaledHeight) { double ch = getRowHeightInPixels(row2 + 1); double delta = h - scaledHeight; dy2 = (int)(EMU_PER_PIXEL*(ch-delta)); } anchor.setRow2(row2); anchor.setDy2(dy2); CTPositiveSize2D size2d = ctPicture.getSpPr().getXfrm().getExt(); size2d.setCx((long)(scaledWidth*EMU_PER_PIXEL)); size2d.setCy((long)(scaledHeight*EMU_PER_PIXEL)); return anchor; }
public XSSFClientAnchor getPreferredSize(double scale){ XSSFClientAnchor anchor = (XSSFClientAnchor)getAnchor(); XSSFPictureData data = getPictureData(); Dimension size = getImageDimension(data.getPackagePart(), data.getPictureType()); double scaledWidth = size.getWidth() * scale; double scaledHeight = size.getHeight() * scale; float w = 0; int col2 = anchor.getCol1(); int dx2 = 0; if(anchor.getDx1() > 0){ w += getColumnWidthInPixels(col2) - anchor.getDx1(); col2++; } for (;;) { w += getColumnWidthInPixels(col2); if(w > scaledWidth) break; col2++; } if(w > scaledWidth) { double cw = getColumnWidthInPixels(col2 + 1); double delta = w - scaledWidth; dx2 = (int)(EMU_PER_PIXEL*(cw-delta)); } anchor.setCol2(col2); anchor.setDx2(dx2); double h = 0; int row2 = anchor.getRow1(); int dy2 = 0; if(anchor.getDy1() > 0){ h += getRowHeightInPixels(row2) - anchor.getDy1()/EMU_PER_PIXEL; row2++; } for (;;) { h += getRowHeightInPixels(row2); if(h > scaledHeight) break; row2++; } if(h > scaledHeight) { double ch = getRowHeightInPixels(row2); double delta = h - scaledHeight; dy2 = (int)(EMU_PER_PIXEL*(ch-delta)); } anchor.setRow2(row2); anchor.setDy2(dy2); CTPositiveSize2D size2d = ctPicture.getSpPr().getXfrm().getExt(); size2d.setCx((long)(scaledWidth*EMU_PER_PIXEL)); size2d.setCy((long)(scaledHeight*EMU_PER_PIXEL)); return anchor; }
diff --git a/src/net/apertoire/vaultee/Server.java b/src/net/apertoire/vaultee/Server.java index 72ae2c0..da418ce 100644 --- a/src/net/apertoire/vaultee/Server.java +++ b/src/net/apertoire/vaultee/Server.java @@ -1,129 +1,129 @@ /* * Copyright 2011-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.apertoire.vaultee; import org.vertx.java.busmods.BusModBase; import org.vertx.java.core.eventbus.Message; import org.vertx.java.core.Handler; import org.vertx.java.core.http.HttpServer; import org.vertx.java.core.http.HttpServerRequest; import org.vertx.java.core.json.JsonArray; import org.vertx.java.core.json.JsonObject; import org.vertx.java.core.sockjs.SockJSServer; import org.vertx.java.core.buffer.Buffer; import java.io.File; import java.util.Map; import java.util.List; import org.jboss.netty.handler.codec.http.QueryStringDecoder; /** * A simple web server module that can serve static files, and also can * bridge event bus messages to/from client side JavaScript and the server side * event bus. * * Please see the modules manual for full description of what configuration * parameters it takes. * * @author <a href="http://tfox.org">Tim Fox</a> */ public class Server extends BusModBase implements Handler<HttpServerRequest> { private String webRootPrefix; private String indexPage; public void start() { super.start(); HttpServer server = vertx.createHttpServer(); if (getOptionalBooleanConfig("ssl", false)) { server.setSSL(true).setKeyStorePassword(getOptionalStringConfig("key_store_password", "wibble")) .setKeyStorePath(getOptionalStringConfig("key_store_path", "server-keystore.jks")); } if (getOptionalBooleanConfig("static_files", true)) { server.requestHandler(this); } boolean bridge = getOptionalBooleanConfig("bridge", false); if (bridge) { SockJSServer sjsServer = vertx.createSockJSServer(server); JsonArray inboundPermitted = getOptionalArrayConfig("inbound_permitted", new JsonArray()); JsonArray outboundPermitted = getOptionalArrayConfig("outbound_permitted", new JsonArray()); sjsServer.bridge(getOptionalObjectConfig("sjs_config", new JsonObject().putString("prefix", "/eventbus")), inboundPermitted, outboundPermitted, getOptionalLongConfig("auth_timeout", 5 * 60 * 1000), getOptionalStringConfig("auth_address", "vaultee.authmanager.authorize")); } String webRoot = getOptionalStringConfig("web_root", "web"); String index = getOptionalStringConfig("index_page", "index.html"); webRootPrefix = webRoot + File.separator; indexPage = webRootPrefix + index; server.listen(getOptionalIntConfig("port", 80), getOptionalStringConfig("host", "0.0.0.0")); logger.info("Server.java service started"); } public void handle(final HttpServerRequest req) { if (req.path.equals("/")) { req.response.sendFile(indexPage); } else if (req.path.equals("/auth")) { req.bodyHandler(new Handler<Buffer>() { @Override public void handle(Buffer buff) { String contentType = req.headers().get("Content-Type"); if ("application/x-www-form-urlencoded".equals(contentType)) { QueryStringDecoder qsd = new QueryStringDecoder(buff.toString(), false); Map<String, List<String>> params = qsd.getParameters(); String email = params.get("email").get(0); String password = params.get("password").get(0); JsonObject args = new JsonObject(); args.putString("email", email); args.putString("password", password); eb.send("vaultee.authmanager.login", args, new Handler<Message<JsonObject>>() { public void handle(Message<JsonObject> reply) { if (getMandatoryString("status", reply).equals("ok")) { req.response.headers().put("Set-Cookie", "vaultee_sessionid=" + getMandatoryString("sessionID", reply)); - req.response.headers().put("Location", "http://blackbeard.apertoire.org:9000/home.html"); + req.response.headers().put("Location", "/home.html"); req.response.statusCode = 302; req.response.end(); } else { req.response.end("life is bad"); } } }); } } }); } else if (!req.path.contains("..")) { logger.info("serving " + req.path); req.response.sendFile(webRootPrefix + req.path); } else { req.response.statusCode = 404; req.response.end(); } } }
true
true
public void handle(final HttpServerRequest req) { if (req.path.equals("/")) { req.response.sendFile(indexPage); } else if (req.path.equals("/auth")) { req.bodyHandler(new Handler<Buffer>() { @Override public void handle(Buffer buff) { String contentType = req.headers().get("Content-Type"); if ("application/x-www-form-urlencoded".equals(contentType)) { QueryStringDecoder qsd = new QueryStringDecoder(buff.toString(), false); Map<String, List<String>> params = qsd.getParameters(); String email = params.get("email").get(0); String password = params.get("password").get(0); JsonObject args = new JsonObject(); args.putString("email", email); args.putString("password", password); eb.send("vaultee.authmanager.login", args, new Handler<Message<JsonObject>>() { public void handle(Message<JsonObject> reply) { if (getMandatoryString("status", reply).equals("ok")) { req.response.headers().put("Set-Cookie", "vaultee_sessionid=" + getMandatoryString("sessionID", reply)); req.response.headers().put("Location", "http://blackbeard.apertoire.org:9000/home.html"); req.response.statusCode = 302; req.response.end(); } else { req.response.end("life is bad"); } } }); } } }); } else if (!req.path.contains("..")) { logger.info("serving " + req.path); req.response.sendFile(webRootPrefix + req.path); } else { req.response.statusCode = 404; req.response.end(); } }
public void handle(final HttpServerRequest req) { if (req.path.equals("/")) { req.response.sendFile(indexPage); } else if (req.path.equals("/auth")) { req.bodyHandler(new Handler<Buffer>() { @Override public void handle(Buffer buff) { String contentType = req.headers().get("Content-Type"); if ("application/x-www-form-urlencoded".equals(contentType)) { QueryStringDecoder qsd = new QueryStringDecoder(buff.toString(), false); Map<String, List<String>> params = qsd.getParameters(); String email = params.get("email").get(0); String password = params.get("password").get(0); JsonObject args = new JsonObject(); args.putString("email", email); args.putString("password", password); eb.send("vaultee.authmanager.login", args, new Handler<Message<JsonObject>>() { public void handle(Message<JsonObject> reply) { if (getMandatoryString("status", reply).equals("ok")) { req.response.headers().put("Set-Cookie", "vaultee_sessionid=" + getMandatoryString("sessionID", reply)); req.response.headers().put("Location", "/home.html"); req.response.statusCode = 302; req.response.end(); } else { req.response.end("life is bad"); } } }); } } }); } else if (!req.path.contains("..")) { logger.info("serving " + req.path); req.response.sendFile(webRootPrefix + req.path); } else { req.response.statusCode = 404; req.response.end(); } }
diff --git a/jmi-server/src/main/java/com/socialcomputing/wps/server/plandictionary/connectors/datastore/DatastoreAffinityGroupReader.java b/jmi-server/src/main/java/com/socialcomputing/wps/server/plandictionary/connectors/datastore/DatastoreAffinityGroupReader.java index 82e5848..efa9040 100644 --- a/jmi-server/src/main/java/com/socialcomputing/wps/server/plandictionary/connectors/datastore/DatastoreAffinityGroupReader.java +++ b/jmi-server/src/main/java/com/socialcomputing/wps/server/plandictionary/connectors/datastore/DatastoreAffinityGroupReader.java @@ -1,155 +1,155 @@ package com.socialcomputing.wps.server.plandictionary.connectors.datastore; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.jdom.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.socialcomputing.wps.server.planDictionnary.connectors.AttributeEnumeratorItem; import com.socialcomputing.wps.server.planDictionnary.connectors.JMIException; import com.socialcomputing.wps.server.plandictionary.AnalysisProfile; import com.socialcomputing.wps.server.plandictionary.connectors.iAffinityGroupReader; import com.socialcomputing.wps.server.plandictionary.connectors.datastore.file.FileEntityConnector; import com.socialcomputing.wps.server.utils.StringAndFloat; public class DatastoreAffinityGroupReader implements iAffinityGroupReader { private final static Logger LOG = LoggerFactory.getLogger(DatastoreAffinityGroupReader.class); protected DatastoreEntityConnector m_entityConnector = null; static DatastoreAffinityGroupReader readObject( Element element) { DatastoreAffinityGroupReader grp = new DatastoreAffinityGroupReader(); return grp; } public void openConnections( DatastoreEntityConnector entityConnector) { m_entityConnector = entityConnector; } public void closeConnections() { } @Override public StringAndFloat[] retrieveAffinityGroup(String id, int affinityThreshold, int max) throws JMIException { StringAndFloat[] result = null; float maxPond = Float.MIN_VALUE; int i = 0; switch( m_entityConnector.m_planType) { case AnalysisProfile.GLOBAL_PLAN: LOG.debug("global plan"); if( m_entityConnector.isInverted()) { result = new StringAndFloat[ m_entityConnector.getAttributes().size()]; for( String id2 : m_entityConnector.getAttributes().keySet()) { result[i++] = new StringAndFloat( id2, 1); } } else { result = new StringAndFloat[ m_entityConnector.getEntities().size()]; for( String id2 : m_entityConnector.getEntities().keySet()) { result[i++] = new StringAndFloat( id2, 1); } } break; case AnalysisProfile.PERSONAL_PLAN: LOG.debug("Personal plan with id = {}", id); Map<String, Integer> set = new HashMap<String, Integer> (); if( m_entityConnector.isInverted()) { if( m_entityConnector.getAttribute(id) == null) throw new JMIException( "Unknonwn entity id " + id); for(String entityId2 : m_entityConnector.getAttribute(id).getEntities()) { for( AttributeEnumeratorItem attributeItem : m_entityConnector.getEntity(entityId2).getAttributes()) { if( set.containsKey( attributeItem.m_Id)) { int pond = set.get( attributeItem.m_Id) + 1; set.put( attributeItem.m_Id, pond); if( pond > maxPond) maxPond = pond; } else { set.put( attributeItem.m_Id, 1); if( maxPond < 1) maxPond = 1; } } } } else { if( m_entityConnector.getEntity(id) == null) throw new JMIException( "Unknonwn entity id " + id); for(AttributeEnumeratorItem attributeItem : m_entityConnector.getEntity(id).getAttributes()) { for( String entityId2 : m_entityConnector.getAttribute(attributeItem.m_Id).getEntities()) { if( set.containsKey( entityId2)) { int pond = set.get( entityId2) + 1; set.put( entityId2, pond); if( pond > maxPond) maxPond = pond; } else { set.put( entityId2, 1); if( maxPond < 1) maxPond = 1; } } } } result = new StringAndFloat[ set.size()]; for( Entry<String, Integer> entry : set.entrySet()) { - result[i++] = new StringAndFloat( entry.getKey(), (maxPond - entry.getValue()) / maxPond); + result[i++] = new StringAndFloat( entry.getKey(), 1 - ((maxPond - entry.getValue())) / maxPond); } break; case AnalysisProfile.DISCOVERY_PLAN: LOG.debug("discovery plan with id = {}", id); Map<String,Integer> set2 = new HashMap<String,Integer>(); if( m_entityConnector.isInverted()) { if( m_entityConnector.getEntity(id) == null) throw new JMIException( "Unknonwn attribute id " + id); for(AttributeEnumeratorItem attributeItem : m_entityConnector.getEntity(id).getAttributes()) { if( set2.containsKey( attributeItem.m_Id)) { int pond = set2.get( attributeItem.m_Id) + 1; set2.put( attributeItem.m_Id, pond); if( pond > maxPond) maxPond = pond; } else { set2.put( attributeItem.m_Id, 1); if( maxPond < 1) maxPond = 1; } } } else { if( m_entityConnector.getAttribute(id) == null) throw new JMIException( "Unknonwn attribute id " + id); for( String entityId : m_entityConnector.getAttribute(id).getEntities()) { if( set2.containsKey( entityId)) { int pond = set2.get( entityId) + 1; set2.put( entityId, pond); if( pond > maxPond) maxPond = pond; } else { set2.put( entityId, 1); if( maxPond < 1) maxPond = 1; } } } result = new StringAndFloat[ set2.size()]; for( Entry<String, Integer> entry : set2.entrySet()) { - result[i++] = new StringAndFloat( entry.getKey(), (maxPond - entry.getValue()) / maxPond); + result[i++] = new StringAndFloat( entry.getKey(), 1 - ((maxPond - entry.getValue()) / maxPond)); } break; } return result; } }
false
true
public StringAndFloat[] retrieveAffinityGroup(String id, int affinityThreshold, int max) throws JMIException { StringAndFloat[] result = null; float maxPond = Float.MIN_VALUE; int i = 0; switch( m_entityConnector.m_planType) { case AnalysisProfile.GLOBAL_PLAN: LOG.debug("global plan"); if( m_entityConnector.isInverted()) { result = new StringAndFloat[ m_entityConnector.getAttributes().size()]; for( String id2 : m_entityConnector.getAttributes().keySet()) { result[i++] = new StringAndFloat( id2, 1); } } else { result = new StringAndFloat[ m_entityConnector.getEntities().size()]; for( String id2 : m_entityConnector.getEntities().keySet()) { result[i++] = new StringAndFloat( id2, 1); } } break; case AnalysisProfile.PERSONAL_PLAN: LOG.debug("Personal plan with id = {}", id); Map<String, Integer> set = new HashMap<String, Integer> (); if( m_entityConnector.isInverted()) { if( m_entityConnector.getAttribute(id) == null) throw new JMIException( "Unknonwn entity id " + id); for(String entityId2 : m_entityConnector.getAttribute(id).getEntities()) { for( AttributeEnumeratorItem attributeItem : m_entityConnector.getEntity(entityId2).getAttributes()) { if( set.containsKey( attributeItem.m_Id)) { int pond = set.get( attributeItem.m_Id) + 1; set.put( attributeItem.m_Id, pond); if( pond > maxPond) maxPond = pond; } else { set.put( attributeItem.m_Id, 1); if( maxPond < 1) maxPond = 1; } } } } else { if( m_entityConnector.getEntity(id) == null) throw new JMIException( "Unknonwn entity id " + id); for(AttributeEnumeratorItem attributeItem : m_entityConnector.getEntity(id).getAttributes()) { for( String entityId2 : m_entityConnector.getAttribute(attributeItem.m_Id).getEntities()) { if( set.containsKey( entityId2)) { int pond = set.get( entityId2) + 1; set.put( entityId2, pond); if( pond > maxPond) maxPond = pond; } else { set.put( entityId2, 1); if( maxPond < 1) maxPond = 1; } } } } result = new StringAndFloat[ set.size()]; for( Entry<String, Integer> entry : set.entrySet()) { result[i++] = new StringAndFloat( entry.getKey(), (maxPond - entry.getValue()) / maxPond); } break; case AnalysisProfile.DISCOVERY_PLAN: LOG.debug("discovery plan with id = {}", id); Map<String,Integer> set2 = new HashMap<String,Integer>(); if( m_entityConnector.isInverted()) { if( m_entityConnector.getEntity(id) == null) throw new JMIException( "Unknonwn attribute id " + id); for(AttributeEnumeratorItem attributeItem : m_entityConnector.getEntity(id).getAttributes()) { if( set2.containsKey( attributeItem.m_Id)) { int pond = set2.get( attributeItem.m_Id) + 1; set2.put( attributeItem.m_Id, pond); if( pond > maxPond) maxPond = pond; } else { set2.put( attributeItem.m_Id, 1); if( maxPond < 1) maxPond = 1; } } } else { if( m_entityConnector.getAttribute(id) == null) throw new JMIException( "Unknonwn attribute id " + id); for( String entityId : m_entityConnector.getAttribute(id).getEntities()) { if( set2.containsKey( entityId)) { int pond = set2.get( entityId) + 1; set2.put( entityId, pond); if( pond > maxPond) maxPond = pond; } else { set2.put( entityId, 1); if( maxPond < 1) maxPond = 1; } } } result = new StringAndFloat[ set2.size()]; for( Entry<String, Integer> entry : set2.entrySet()) { result[i++] = new StringAndFloat( entry.getKey(), (maxPond - entry.getValue()) / maxPond); } break; } return result; }
public StringAndFloat[] retrieveAffinityGroup(String id, int affinityThreshold, int max) throws JMIException { StringAndFloat[] result = null; float maxPond = Float.MIN_VALUE; int i = 0; switch( m_entityConnector.m_planType) { case AnalysisProfile.GLOBAL_PLAN: LOG.debug("global plan"); if( m_entityConnector.isInverted()) { result = new StringAndFloat[ m_entityConnector.getAttributes().size()]; for( String id2 : m_entityConnector.getAttributes().keySet()) { result[i++] = new StringAndFloat( id2, 1); } } else { result = new StringAndFloat[ m_entityConnector.getEntities().size()]; for( String id2 : m_entityConnector.getEntities().keySet()) { result[i++] = new StringAndFloat( id2, 1); } } break; case AnalysisProfile.PERSONAL_PLAN: LOG.debug("Personal plan with id = {}", id); Map<String, Integer> set = new HashMap<String, Integer> (); if( m_entityConnector.isInverted()) { if( m_entityConnector.getAttribute(id) == null) throw new JMIException( "Unknonwn entity id " + id); for(String entityId2 : m_entityConnector.getAttribute(id).getEntities()) { for( AttributeEnumeratorItem attributeItem : m_entityConnector.getEntity(entityId2).getAttributes()) { if( set.containsKey( attributeItem.m_Id)) { int pond = set.get( attributeItem.m_Id) + 1; set.put( attributeItem.m_Id, pond); if( pond > maxPond) maxPond = pond; } else { set.put( attributeItem.m_Id, 1); if( maxPond < 1) maxPond = 1; } } } } else { if( m_entityConnector.getEntity(id) == null) throw new JMIException( "Unknonwn entity id " + id); for(AttributeEnumeratorItem attributeItem : m_entityConnector.getEntity(id).getAttributes()) { for( String entityId2 : m_entityConnector.getAttribute(attributeItem.m_Id).getEntities()) { if( set.containsKey( entityId2)) { int pond = set.get( entityId2) + 1; set.put( entityId2, pond); if( pond > maxPond) maxPond = pond; } else { set.put( entityId2, 1); if( maxPond < 1) maxPond = 1; } } } } result = new StringAndFloat[ set.size()]; for( Entry<String, Integer> entry : set.entrySet()) { result[i++] = new StringAndFloat( entry.getKey(), 1 - ((maxPond - entry.getValue())) / maxPond); } break; case AnalysisProfile.DISCOVERY_PLAN: LOG.debug("discovery plan with id = {}", id); Map<String,Integer> set2 = new HashMap<String,Integer>(); if( m_entityConnector.isInverted()) { if( m_entityConnector.getEntity(id) == null) throw new JMIException( "Unknonwn attribute id " + id); for(AttributeEnumeratorItem attributeItem : m_entityConnector.getEntity(id).getAttributes()) { if( set2.containsKey( attributeItem.m_Id)) { int pond = set2.get( attributeItem.m_Id) + 1; set2.put( attributeItem.m_Id, pond); if( pond > maxPond) maxPond = pond; } else { set2.put( attributeItem.m_Id, 1); if( maxPond < 1) maxPond = 1; } } } else { if( m_entityConnector.getAttribute(id) == null) throw new JMIException( "Unknonwn attribute id " + id); for( String entityId : m_entityConnector.getAttribute(id).getEntities()) { if( set2.containsKey( entityId)) { int pond = set2.get( entityId) + 1; set2.put( entityId, pond); if( pond > maxPond) maxPond = pond; } else { set2.put( entityId, 1); if( maxPond < 1) maxPond = 1; } } } result = new StringAndFloat[ set2.size()]; for( Entry<String, Integer> entry : set2.entrySet()) { result[i++] = new StringAndFloat( entry.getKey(), 1 - ((maxPond - entry.getValue()) / maxPond)); } break; } return result; }
diff --git a/javafx.editor/src/org/netbeans/modules/javafx/editor/completion/environment/FunctionValueEnvironment.java b/javafx.editor/src/org/netbeans/modules/javafx/editor/completion/environment/FunctionValueEnvironment.java index 518677f4..b3840742 100644 --- a/javafx.editor/src/org/netbeans/modules/javafx/editor/completion/environment/FunctionValueEnvironment.java +++ b/javafx.editor/src/org/netbeans/modules/javafx/editor/completion/environment/FunctionValueEnvironment.java @@ -1,97 +1,97 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * Contributor(s): * * Portions Copyrighted 2008 Sun Microsystems, Inc. */ package org.netbeans.modules.javafx.editor.completion.environment; import com.sun.javafx.api.tree.ExpressionTree; import com.sun.javafx.api.tree.JavaFXTreePath; import com.sun.javafx.api.tree.Tree; import com.sun.javafx.api.tree.TryTree; import com.sun.tools.javafx.tree.JFXBlock; import com.sun.tools.javafx.tree.JFXFunctionValue; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.tools.Diagnostic; import org.netbeans.modules.javafx.editor.completion.JavaFXCompletionEnvironment; import static org.netbeans.modules.javafx.editor.completion.JavaFXCompletionQuery.*; /** * * @author David Strupl */ public class FunctionValueEnvironment extends JavaFXCompletionEnvironment<JFXFunctionValue> { private static final Logger logger = Logger.getLogger(FunctionValueEnvironment.class.getName()); private static final boolean LOGGABLE = logger.isLoggable(Level.FINE); @Override protected void inside(JFXFunctionValue val) throws IOException { if (LOGGABLE) log("inside JFXFunctionValue " + val); JFXBlock bl = val.getBodyExpression(); if (bl != null) { ExpressionTree last = null; for (ExpressionTree stat : bl.getStatements()) { int pos = (int) sourcePositions.getStartPosition(root, stat); if (pos == Diagnostic.NOPOS || offset <= pos) { break; } last = stat; } if (last != null && last.getJavaFXKind() == Tree.JavaFXKind.TRY) { if (((TryTree) last).getFinallyBlock() == null) { addKeyword(CATCH_KEYWORD, null, false); addKeyword(FINALLY_KEYWORD, null, false); if (((TryTree) last).getCatches().size() == 0) { return; } } } + path = JavaFXTreePath.getPath(root, bl); + localResult(null); + addKeywordsForStatement(); } - path = JavaFXTreePath.getPath(root, bl); - localResult(null); - addKeywordsForStatement(); } private static void log(String s) { if (LOGGABLE) { logger.fine(s); } } }
false
true
protected void inside(JFXFunctionValue val) throws IOException { if (LOGGABLE) log("inside JFXFunctionValue " + val); JFXBlock bl = val.getBodyExpression(); if (bl != null) { ExpressionTree last = null; for (ExpressionTree stat : bl.getStatements()) { int pos = (int) sourcePositions.getStartPosition(root, stat); if (pos == Diagnostic.NOPOS || offset <= pos) { break; } last = stat; } if (last != null && last.getJavaFXKind() == Tree.JavaFXKind.TRY) { if (((TryTree) last).getFinallyBlock() == null) { addKeyword(CATCH_KEYWORD, null, false); addKeyword(FINALLY_KEYWORD, null, false); if (((TryTree) last).getCatches().size() == 0) { return; } } } } path = JavaFXTreePath.getPath(root, bl); localResult(null); addKeywordsForStatement(); }
protected void inside(JFXFunctionValue val) throws IOException { if (LOGGABLE) log("inside JFXFunctionValue " + val); JFXBlock bl = val.getBodyExpression(); if (bl != null) { ExpressionTree last = null; for (ExpressionTree stat : bl.getStatements()) { int pos = (int) sourcePositions.getStartPosition(root, stat); if (pos == Diagnostic.NOPOS || offset <= pos) { break; } last = stat; } if (last != null && last.getJavaFXKind() == Tree.JavaFXKind.TRY) { if (((TryTree) last).getFinallyBlock() == null) { addKeyword(CATCH_KEYWORD, null, false); addKeyword(FINALLY_KEYWORD, null, false); if (((TryTree) last).getCatches().size() == 0) { return; } } } path = JavaFXTreePath.getPath(root, bl); localResult(null); addKeywordsForStatement(); } }
diff --git a/src/main/java/org/jboss/cluster/proxy/container/MCMPAdapter.java b/src/main/java/org/jboss/cluster/proxy/container/MCMPAdapter.java index 0003184..280fde1 100644 --- a/src/main/java/org/jboss/cluster/proxy/container/MCMPAdapter.java +++ b/src/main/java/org/jboss/cluster/proxy/container/MCMPAdapter.java @@ -1,772 +1,772 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.jboss.cluster.proxy.container; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; import java.security.MessageDigest; import java.sql.Date; import java.util.Arrays; import java.util.Enumeration; import java.util.UUID; import org.apache.catalina.connector.Connector; import org.apache.coyote.ActionCode; import org.apache.coyote.Adapter; import org.apache.coyote.Request; import org.apache.coyote.Response; import org.apache.coyote.http11.Constants; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.Parameters; import org.apache.tomcat.util.net.SocketStatus; import org.jboss.cluster.proxy.container.Context.Status; /** * Adapter. This represents the entry point in a coyote-based servlet container. * reads the MCM element * * @author Jean-Frederic Clere * */ public class MCMPAdapter implements Adapter { private static final String VERSION_PROTOCOL = "0.2.1"; private static final String TYPESYNTAX = "SYNTAX"; private static final String TYPEMEM = "MEM"; /* the syntax error messages */ private static final String SMESPAR = "SYNTAX: Can't parse message"; private static final String SBALBIG = "SYNTAX: Balancer field too big"; private static final String SBAFBIG = "SYNTAX: A field is too big"; private static final String SROUBIG = "SYNTAX: JVMRoute field too big"; private static final String SROUBAD = "SYNTAX: JVMRoute can't be empty"; private static final String SDOMBIG = "SYNTAX: LBGroup field too big"; private static final String SHOSBIG = "SYNTAX: Host field too big"; private static final String SPORBIG = "SYNTAX: Port field too big"; private static final String STYPBIG = "SYNTAX: Type field too big"; private static final String SALIBAD = "SYNTAX: Alias without Context"; private static final String SCONBAD = "SYNTAX: Context without Alias"; private static final String SBADFLD = "SYNTAX: Invalid field "; private static final String SBADFLD1 = " in message"; private static final String SMISFLD = "SYNTAX: Mandatory field(s) missing in message"; private static final String SCMDUNS = "SYNTAX: Command is not supported"; private static final String SMULALB = "SYNTAX: Only one Alias in APP command"; private static final String SMULCTB = "SYNTAX: Only one Context in APP command"; private static final String SREADER = "SYNTAX: %s can't read POST data"; /* the mem error messages */ private static final String MNODEUI = "MEM: Can't update or insert node"; private static final String MNODERM = "MEM: Old node still exist"; private static final String MBALAUI = "MEM: Can't update or insert balancer"; private static final String MNODERD = "MEM: Can't read node"; private static final String MHOSTRD = "MEM: Can't read host alias"; private static final String MHOSTUI = "MEM: Can't update or insert host alias"; private static final String MCONTUI = "MEM: Can't update or insert context"; static final byte[] CRLF = "\r\n".getBytes(); private Connector connector; protected Thread thread = null; private String sgroup = "224.0.1.105"; private int sport = 23364; private String slocal = "127.0.0.1"; private MessageDigest md = null; private String chost = "127.0.0.1"; // System.getProperty("org.jboss.cluster.proxy.net.ADDRESS", // "127.0.0.1"); private int cport = Integer.parseInt(System.getProperty("org.jboss.cluster.proxy.net.PORT", "6666")); private String scheme = "http"; private String securityKey = System .getProperty("org.jboss.cluster.proxy.securityKey", "secret"); /** * Create a new instance of {@code MCMPaddapter} * * @param connector */ public MCMPAdapter(Connector connector) { this.connector = connector; this.scheme = connector.getScheme(); } /* * (non-Javadoc) * * @see org.apache.coyote.Adapter#init() */ public void init() throws Exception { System.out.println("init: " + connector); if (md == null) md = MessageDigest.getInstance("MD5"); if (thread == null) { thread = new Thread(new MCMAdapterBackgroundProcessor(), "MCMAdapaterBackgroundProcessor"); thread.setDaemon(true); thread.start(); } } protected class MCMAdapterBackgroundProcessor implements Runnable { /* * the messages to send are something like: * * HTTP/1.0 200 OK * Date: Thu, 13 Sep 2012 09:24:02 GMT * Sequence: 5 * Digest: ae8e7feb7cd85be346134657de3b0661 * Server: b58743ba-fd84-11e1-bd12-ad866be2b4cc * X-Manager-Address: 127.0.0.1:6666 * X-Manager-Url: /b58743ba-fd84-11e1-bd12-ad866be2b4cc * X-Manager-Protocol: http * X-Manager-Host: 10.33.144.3 * non-Javadoc) */ @Override public void run() { try { InetAddress group = InetAddress.getByName(sgroup); InetAddress addr = InetAddress.getByName(slocal); InetSocketAddress addrs = new InetSocketAddress(sport); MulticastSocket s = new MulticastSocket(addrs); s.setTimeToLive(29); s.joinGroup(group); int seq = 0; /* * apr_uuid_get(&magd->suuid); * magd->srvid[0] = '/'; * apr_uuid_format(&magd->srvid[1], &magd->suuid); * In fact we use the srvid on the 2 second byte [1] */ String server = UUID.randomUUID().toString(); boolean ok = true; while (ok) { Date date = new Date(System.currentTimeMillis()); md.reset(); digestString(md, securityKey); byte[] ssalt = md.digest(); md.update(ssalt); digestString(md, date); digestString(md, seq); digestString(md, server); byte[] digest = md.digest(); StringBuilder str = new StringBuilder(); for (int i = 0; i < digest.length; i++) str.append(String.format("%x", digest[i])); String sbuf = "HTTP/1.0 200 OK\r\n" + "Date: " + date + "\r\n" + "Sequence: " + seq + "\r\n" + "Digest: " + str.toString() + "\r\n" + "Server: " + server + "\r\n" + "X-Manager-Address: " + chost + ":" + cport + "\r\n" + "X-Manager-Url: /" + server + "\r\n" + "X-Manager-Protocol: " + scheme + "\r\n" + "X-Manager-Host: " + chost + "\r\n"; byte[] buf = sbuf.getBytes(); DatagramPacket data = new DatagramPacket(buf, buf.length, group, sport); s.send(data); Thread.sleep(1000); seq++; } s.leaveGroup(group); } catch (Exception Ex) { Ex.printStackTrace(System.out); } } private void digestString(MessageDigest md, int seq) { String sseq = "" + seq; digestString(md, sseq); } private void digestString(MessageDigest md, Date date) { String sdate = date.toString(); digestString(md, sdate); } private void digestString(MessageDigest md, String securityKey) { byte buf[] = securityKey.getBytes(); md.update(buf); } } /* * (non-Javadoc) * * @see org.apache.coyote.Adapter#event(org.apache.coyote.Request, * org.apache.coyote.Response, org.apache.tomcat.util.net.SocketStatus) */ public boolean event(Request req, Response res, SocketStatus status) throws Exception { return false; } static MCMConfig conf = new MCMConfig(); /* * (non-Javadoc) * * @see org.apache.coyote.Adapter#service(org.apache.coyote.Request, * org.apache.coyote.Response) */ public void service(Request req, Response res) throws Exception { System.out.println("service..."); MessageBytes methodMB = req.method(); if (methodMB.equals(Constants.GET)) { // In fact that is /mod_cluster_manager } else if (methodMB.equals(Constants.CONFIG)) { process_config(req, res); } else if (methodMB.equals(Constants.ENABLE_APP)) { try { process_enable(req, res); } catch (Exception Ex) { Ex.printStackTrace(System.out); } } else if (methodMB.equals(Constants.DISABLE_APP)) { process_disable(req, res); } else if (methodMB.equals(Constants.STOP_APP)) { process_stop(req, res); } else if (methodMB.equals(Constants.REMOVE_APP)) { try { process_remove(req, res); } catch (Exception Ex) { Ex.printStackTrace(System.out); } } else if (methodMB.equals(Constants.STATUS)) { process_status(req, res); } else if (methodMB.equals(Constants.DUMP)) { process_dump(req, res); } else if (methodMB.equals(Constants.INFO)) { try { process_info(req, res); } catch (Exception Ex) { Ex.printStackTrace(System.out); } } else if (methodMB.equals(Constants.PING)) { process_ping(req, res); } res.sendHeaders(); if (!res.isCommitted()) { // If the response is not committed, then commit res.action(ActionCode.ACTION_COMMIT, res); } // Flush buffers res.action(ActionCode.ACTION_CLIENT_FLUSH, res); } /** * Process <tt>PING</tt> request * * @param req * @param res * @throws Exception */ private void process_ping(Request req, Response res) throws Exception { System.out.println("process_ping"); Parameters params = req.getParameters(); if (params == null) { process_error(TYPESYNTAX, SMESPAR, res); return; } String jvmRoute = null; String scheme = null; String host = null; String port = null; Enumeration<String> names = params.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String[] value = params.getParameterValues(name); if (name.equalsIgnoreCase("JVMRoute")) { jvmRoute = value[0]; } else if (name.equalsIgnoreCase("Scheme")) { scheme = value[0]; } else if (name.equalsIgnoreCase("Port")) { port = value[0]; } else if (name.equalsIgnoreCase("Host")) { host = value[0]; } else { process_error(TYPESYNTAX, SBADFLD + name + SBADFLD1, res); return; } } if (jvmRoute == null) { if (scheme == null && host == null && port == null) { res.addHeader("Content-Type", "text/plain"); String data = "Type=PING-RSP&State=OK"; res.setContentLength(data.length()); ByteChunk chunk = new ByteChunk(); chunk.append(data.getBytes(), 0, data.length()); res.doWrite(chunk); return; } else { if (scheme == null || host == null || port == null) { process_error(TYPESYNTAX, SMISFLD, res); return; } res.addHeader("Content-Type", "text/plain"); - String data = "Type=PING-RSP&State=OK"; + String data = "Type=PING-RSP"; if (ishost_up(scheme, host, port)) data = data.concat("&State=OK"); else data = data.concat("&State=NOTOK"); res.setContentLength(data.length()); ByteChunk chunk = new ByteChunk(); chunk.append(data.getBytes(), 0, data.length()); res.doWrite(chunk); } } else { // ping the corresponding node. Node node = conf.getNode(jvmRoute); if (node == null) { process_error(TYPEMEM, MNODERD, res); return; } res.addHeader("Content-Type", "text/plain"); - String data = "Type=PING-RSP&State=OK"; + String data = "Type=PING-RSP"; if (isnode_up(node)) data = data.concat("&State=OK"); else data = data.concat("&State=NOTOK"); res.setContentLength(data.length()); ByteChunk chunk = new ByteChunk(); chunk.append(data.getBytes(), 0, data.length()); res.doWrite(chunk); } } private boolean isnode_up(Node node) { System.out.println("process_ping: " + node); return false; } private boolean ishost_up(String scheme, String host, String port) { System.out.println("process_ping: " + scheme + "://" + host + ":" + port); return false; } /* * Something like: * * Node: [1],Name: 368e2e5c-d3f7-3812-9fc6-f96d124dcf79,Balancer: * cluster-prod-01,LBGroup: ,Host: 127.0.0.1,Port: 8443,Type: * https,Flushpackets: Off,Flushwait: 10,Ping: 10,Smax: 21,Ttl: 60,Elected: * 0,Read: 0,Transfered: 0,Connected: 0,Load: 1 Vhost: [1:1:1], Alias: * default-host Vhost: [1:1:2], Alias: localhost Vhost: [1:1:3], Alias: * example.com Context: [1:1:1], Context: /myapp, Status: ENABLED */ /** * Process <tt>INFO</tt> request * * @param req * @param res * @throws Exception */ private void process_info(Request req, Response res) throws Exception { String data = process_info_string(); process_OK(res); res.addHeader("Content-Type", "text/plain"); res.addHeader("Server", "Mod_CLuster/0.0.0"); if (data.length() > 0) { res.setContentLength(data.length()); } ByteChunk chunk = new ByteChunk(); chunk.append(data.getBytes(), 0, data.length()); res.doWrite(chunk); } private String process_info_string() { int i = 1; StringBuilder data = new StringBuilder(); for (Node node : conf.getNodes()) { data.append("Node: [").append(i).append("],Name: ").append(node.getJvmRoute()) .append(",Balancer: ").append(node.getBalancer()).append(",LBGroup: ") .append(node.getDomain()).append(",Host: ").append(node.getHostname()) .append(",Port: ").append(node.getPort()).append(",Type: ") .append(node.getType()).append(",Flushpackets: ") .append((node.isFlushpackets() ? "On" : "Off")).append(",Flushwait: ") .append(node.getFlushwait()).append(",Ping: ").append(node.getPing()) .append(",Smax: ").append(node.getSmax()).append(",Ttl: ") .append(node.getTtl()).append(",Elected: ").append(node.getElected()) .append(",Read: ").append(node.getRead()).append(",Transfered: ") .append(node.getTransfered()).append(",Connected: ") .append(node.getConnected()).append(",Load: ").append(node.getLoad() + "\n"); i++; } for (VHost host : conf.getHosts()) { int j = 1; long node = conf.getNodeId(host.getJVMRoute()); for (String alias : host.getAliases()) { data.append("Vhost: [").append(node).append(":").append(host.getId()).append(":") .append(j).append("], Alias: ").append(alias).append("\n"); j++; } } i = 1; for (Context context : conf.getContexts()) { data.append("Context: [").append(conf.getNodeId(context.getJVMRoute())).append(":") .append(context.getHostId()).append(":").append(i).append("], Context: ") .append(context.getPath()).append(", Status: ").append(context.getStatus()) .append("\n"); // TODO do we need to increment i ? // i++; } return data.toString(); } /* * something like: * * balancer: [1] Name: cluster-prod-01 Sticky: 1 [JSESSIONID]/[jsessionid] * remove: 0 force: 0 Timeout: 0 maxAttempts: 1 node: [1:1],Balancer: * cluster-prod-01,JVMRoute: 368e2e5c-d3f7-3812-9fc6-f96d124dcf79,LBGroup: * [],Host: 127.0.0.1,Port: 8443,Type: https,flushpackets: 0,flushwait: * 10,ping: 10,smax: 21,ttl: 60,timeout: 0 host: 1 [default-host] vhost: 1 * node: 1 host: 2 [localhost] vhost: 1 node: 1 host: 3 [example.com] vhost: * 1 node: 1 context: 1 [/myapp] vhost: 1 node: 1 status: 1 */ /** * Process <tt>DUMP</tt> request * * @param req * @param res */ private void process_dump(Request req, Response res) { String data = ""; int i = 1; for (Balancer balancer : conf.getBalancers()) { String bal = "balancer: [" + i + "] Name: " + balancer.getName() + " Sticky: " + (balancer.isStickySession() ? "1" : "0") + " [" + balancer.getStickySessionCookie() + "]/[" + balancer.getStickySessionPath() + "] remove: " + (balancer.isStickySessionRemove() ? "1" : "0") + " force: " + (balancer.isStickySessionForce() ? "1" : "0") + " Timeout: " + balancer.getWaitWorker() + " maxAttempts: " + balancer.getMaxattempts() + "\n"; data = data.concat(bal); i++; } // TODO Add more... System.out.println("process_dump"); } /** * Process <tt>STATUS</tt> request * * @param req * @param res * @throws Exception */ private void process_status(Request req, Response res) throws Exception { Parameters params = req.getParameters(); if (params == null) { process_error(TYPESYNTAX, SMESPAR, res); return; } String jvmRoute = null; String load = null; Enumeration<String> names = params.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String[] value = params.getParameterValues(name); if (name.equalsIgnoreCase("JVMRoute")) { jvmRoute = value[0]; } else if (name.equalsIgnoreCase("Load")) { load = value[0]; } else { process_error(TYPESYNTAX, SBADFLD + value[0] + SBADFLD1, res); return; } } if (load == null || jvmRoute == null) { process_error(TYPESYNTAX, SMISFLD, res); return; } Node node = conf.getNode(jvmRoute); if (node == null) { process_error(TYPEMEM, MNODERD, res); return; } node.setLoad(Integer.parseInt(load)); /* TODO we need to check the node here */ node.setStatus(Node.NodeStatus.NODE_UP); process_OK(res); } /** * Process <tt>REMOVE-APP</tt> request * * @param req * @param res * @throws Exception */ private void process_remove(Request req, Response res) throws Exception { Parameters params = req.getParameters(); if (params == null) { process_error(TYPESYNTAX, SMESPAR, res); return; } boolean global = false; if (req.unparsedURI().toString().equals("*") || req.unparsedURI().toString().endsWith("/*")) { global = true; } Context context = new Context(); VHost host = new VHost(); Enumeration<String> names = params.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String[] value = params.getParameterValues(name); if (name.equalsIgnoreCase("JVMRoute")) { if (conf.getNodeId(value[0]) == -1) { process_error(TYPEMEM, MNODERD, res); return; } host.setJVMRoute(value[0]); context.setJVMRoute(value[0]); } else if (name.equalsIgnoreCase("Alias")) { // Alias is something like =default-host,localhost,example.com String aliases[] = value[0].split(","); host.setAliases(Arrays.asList(aliases)); } else if (name.equalsIgnoreCase("Context")) { context.setPath(value[0]); } } if (context.getJVMRoute() == null) { process_error(TYPESYNTAX, SROUBAD, res); return; } if (global) conf.removeNode(context.getJVMRoute()); else conf.remove(context, host); process_OK(res); } /** * Process <tt>STOP-APP</tt> request * * @param req * @param res * @throws Exception */ private void process_stop(Request req, Response res) throws Exception { process_cmd(req, res, Context.Status.STOPPED); } /** * Process <tt>DISABLE-APP</tt> request * * @param req * @param res * @throws Exception */ private void process_disable(Request req, Response res) throws Exception { process_cmd(req, res, Context.Status.DISABLED); } /** * Process <tt>ENABLE-APP</tt> request * * @param req * @param res * @throws Exception */ private void process_enable(Request req, Response res) throws Exception { process_cmd(req, res, Context.Status.ENABLED); } private void process_cmd(Request req, Response res, Context.Status status) throws Exception { Parameters params = req.getParameters(); if (params == null) { process_error(TYPESYNTAX, SMESPAR, res); return; } if (req.unparsedURI().toString().equals("*") || req.unparsedURI().toString().endsWith("/*")) { process_node_cmd(req, res, status); return; } Context context = new Context(); VHost host = new VHost(); Enumeration<String> names = params.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String[] value = params.getParameterValues(name); if (name.equalsIgnoreCase("JVMRoute")) { if (conf.getNodeId(value[0]) == -1) { process_error(TYPEMEM, MNODERD, res); return; } host.setJVMRoute(value[0]); context.setJVMRoute(value[0]); } else if (name.equalsIgnoreCase("Alias")) { // Alias is something like =default-host,localhost,example.com String aliases[] = value[0].split(","); host.setAliases(Arrays.asList(aliases)); } else if (name.equalsIgnoreCase("Context")) { context.setPath(value[0]); } } if (context.getJVMRoute() == null) { process_error(TYPESYNTAX, SROUBAD, res); return; } context.setStatus(status); long id = conf.insertupdate(host); context.setHostid(id); conf.insertupdate(context); process_OK(res); } private void process_node_cmd(Request req, Response res, Status enabled) { System.out.println("process_node_cmd:" + process_info_string()); } /** * Process <tt>CONFIG</tt> request * * @param req * @param res * @throws Exception */ private void process_config(Request req, Response res) throws Exception { Parameters params = req.getParameters(); if (params == null) { process_error(TYPESYNTAX, SMESPAR, res); return; } Balancer balancer = new Balancer(); Node node = new Node(); Enumeration<String> names = params.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String[] value = params.getParameterValues(name); if (name.equalsIgnoreCase("Balancer")) { balancer.setName(value[0]); node.setBalancer(value[0]); } else if (name.equalsIgnoreCase("StickySession")) { if (value[0].equalsIgnoreCase("No")) balancer.setStickySession(false); } else if (name.equalsIgnoreCase("StickySessionCookie")) { balancer.setStickySessionCookie(value[0]); } else if (name.equalsIgnoreCase("StickySessionPath")) { balancer.setStickySessionPath(value[0]); } else if (name.equalsIgnoreCase("StickySessionRemove")) { if (value[0].equalsIgnoreCase("Yes")) balancer.setStickySessionRemove(true); } else if (name.equalsIgnoreCase("StickySessionForce")) { if (value[0].equalsIgnoreCase("no")) balancer.setStickySessionForce(false); } else if (name.equalsIgnoreCase("WaitWorker")) { balancer.setWaitWorker(Integer.valueOf(value[0])); } else if (name.equalsIgnoreCase("Maxattempts")) { balancer.setMaxattempts(Integer.valueOf(value[0])); } else if (name.equalsIgnoreCase("JVMRoute")) { node.setJvmRoute(value[0]); } else if (name.equalsIgnoreCase("Domain")) { node.setDomain(value[0]); } else if (name.equalsIgnoreCase("Host")) { node.setHostname(value[0]); } else if (name.equalsIgnoreCase("Port")) { node.setPort(Integer.valueOf(value[0])); } else if (name.equalsIgnoreCase("Type")) { node.setType(value[0]); } else if (name.equalsIgnoreCase("Reversed")) { continue; // ignore it. } else if (name.equalsIgnoreCase("flushpacket")) { if (value[0].equalsIgnoreCase("on")) node.setFlushpackets(true); if (value[0].equalsIgnoreCase("auto")) node.setFlushpackets(true); } else if (name.equalsIgnoreCase("flushwait")) { node.setFlushwait(Integer.valueOf(value[0])); } else if (name.equalsIgnoreCase("ping")) { node.setPing(Integer.valueOf(value[0])); } else if (name.equalsIgnoreCase("smax")) { node.setSmax(Integer.valueOf(value[0])); } else if (name.equalsIgnoreCase("ttl")) { node.setTtl(Integer.valueOf(value[0])); } else if (name.equalsIgnoreCase("Timeout")) { node.setTimeout(Integer.valueOf(value[0])); } else { process_error(TYPESYNTAX, SBADFLD + name + SBADFLD1, res); return; } } conf.insertupdate(balancer); conf.insertupdate(node); process_OK(res); } /** * If the process is OK, then add 200 HTTP status and its "OK" phrase * * @param res * @throws Exception */ private void process_OK(Response res) throws Exception { res.setStatus(200); res.setMessage("OK"); res.addHeader("Content-type", "plain/text"); } /** * If any error occurs, * * @param type * @param errstring * @param res * @throws Exception */ private void process_error(String type, String errstring, Response res) throws Exception { res.setStatus(500); res.setMessage("ERROR"); res.addHeader("Version", VERSION_PROTOCOL); res.addHeader("Type", type); res.addHeader("Mess", errstring); } }
false
true
private void process_ping(Request req, Response res) throws Exception { System.out.println("process_ping"); Parameters params = req.getParameters(); if (params == null) { process_error(TYPESYNTAX, SMESPAR, res); return; } String jvmRoute = null; String scheme = null; String host = null; String port = null; Enumeration<String> names = params.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String[] value = params.getParameterValues(name); if (name.equalsIgnoreCase("JVMRoute")) { jvmRoute = value[0]; } else if (name.equalsIgnoreCase("Scheme")) { scheme = value[0]; } else if (name.equalsIgnoreCase("Port")) { port = value[0]; } else if (name.equalsIgnoreCase("Host")) { host = value[0]; } else { process_error(TYPESYNTAX, SBADFLD + name + SBADFLD1, res); return; } } if (jvmRoute == null) { if (scheme == null && host == null && port == null) { res.addHeader("Content-Type", "text/plain"); String data = "Type=PING-RSP&State=OK"; res.setContentLength(data.length()); ByteChunk chunk = new ByteChunk(); chunk.append(data.getBytes(), 0, data.length()); res.doWrite(chunk); return; } else { if (scheme == null || host == null || port == null) { process_error(TYPESYNTAX, SMISFLD, res); return; } res.addHeader("Content-Type", "text/plain"); String data = "Type=PING-RSP&State=OK"; if (ishost_up(scheme, host, port)) data = data.concat("&State=OK"); else data = data.concat("&State=NOTOK"); res.setContentLength(data.length()); ByteChunk chunk = new ByteChunk(); chunk.append(data.getBytes(), 0, data.length()); res.doWrite(chunk); } } else { // ping the corresponding node. Node node = conf.getNode(jvmRoute); if (node == null) { process_error(TYPEMEM, MNODERD, res); return; } res.addHeader("Content-Type", "text/plain"); String data = "Type=PING-RSP&State=OK"; if (isnode_up(node)) data = data.concat("&State=OK"); else data = data.concat("&State=NOTOK"); res.setContentLength(data.length()); ByteChunk chunk = new ByteChunk(); chunk.append(data.getBytes(), 0, data.length()); res.doWrite(chunk); } }
private void process_ping(Request req, Response res) throws Exception { System.out.println("process_ping"); Parameters params = req.getParameters(); if (params == null) { process_error(TYPESYNTAX, SMESPAR, res); return; } String jvmRoute = null; String scheme = null; String host = null; String port = null; Enumeration<String> names = params.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String[] value = params.getParameterValues(name); if (name.equalsIgnoreCase("JVMRoute")) { jvmRoute = value[0]; } else if (name.equalsIgnoreCase("Scheme")) { scheme = value[0]; } else if (name.equalsIgnoreCase("Port")) { port = value[0]; } else if (name.equalsIgnoreCase("Host")) { host = value[0]; } else { process_error(TYPESYNTAX, SBADFLD + name + SBADFLD1, res); return; } } if (jvmRoute == null) { if (scheme == null && host == null && port == null) { res.addHeader("Content-Type", "text/plain"); String data = "Type=PING-RSP&State=OK"; res.setContentLength(data.length()); ByteChunk chunk = new ByteChunk(); chunk.append(data.getBytes(), 0, data.length()); res.doWrite(chunk); return; } else { if (scheme == null || host == null || port == null) { process_error(TYPESYNTAX, SMISFLD, res); return; } res.addHeader("Content-Type", "text/plain"); String data = "Type=PING-RSP"; if (ishost_up(scheme, host, port)) data = data.concat("&State=OK"); else data = data.concat("&State=NOTOK"); res.setContentLength(data.length()); ByteChunk chunk = new ByteChunk(); chunk.append(data.getBytes(), 0, data.length()); res.doWrite(chunk); } } else { // ping the corresponding node. Node node = conf.getNode(jvmRoute); if (node == null) { process_error(TYPEMEM, MNODERD, res); return; } res.addHeader("Content-Type", "text/plain"); String data = "Type=PING-RSP"; if (isnode_up(node)) data = data.concat("&State=OK"); else data = data.concat("&State=NOTOK"); res.setContentLength(data.length()); ByteChunk chunk = new ByteChunk(); chunk.append(data.getBytes(), 0, data.length()); res.doWrite(chunk); } }
diff --git a/CubicTestSeleniumExporter/src/main/java/org/cubictest/exporters/selenium/runner/converters/TransitionConverter.java b/CubicTestSeleniumExporter/src/main/java/org/cubictest/exporters/selenium/runner/converters/TransitionConverter.java index 54e4155a..296e27b4 100644 --- a/CubicTestSeleniumExporter/src/main/java/org/cubictest/exporters/selenium/runner/converters/TransitionConverter.java +++ b/CubicTestSeleniumExporter/src/main/java/org/cubictest/exporters/selenium/runner/converters/TransitionConverter.java @@ -1,178 +1,184 @@ /******************************************************************************* * Copyright (c) 2005, 2008 Christian Schwarz and Stein K. Skytteren * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Christian Schwarz and Stein K. Skytteren - initial API and implementation *******************************************************************************/ package org.cubictest.exporters.selenium.runner.converters; import org.cubictest.common.utils.ErrorHandler; import org.cubictest.common.utils.Logger; import org.cubictest.export.converters.ITransitionConverter; import org.cubictest.export.exceptions.ExporterException; import org.cubictest.export.exceptions.UserInteractionException; import org.cubictest.exporters.selenium.runner.holders.CubicTestLocalRunner; import org.cubictest.exporters.selenium.runner.holders.SeleniumHolder; import org.cubictest.exporters.selenium.utils.SeleniumUtils; import org.cubictest.model.ActionType; import org.cubictest.model.IActionElement; import org.cubictest.model.OnOffAutoTriState; import org.cubictest.model.PageElement; import org.cubictest.model.TestPartStatus; import org.cubictest.model.UserInteraction; import org.cubictest.model.UserInteractionsTransition; import org.cubictest.model.WebBrowser; import org.cubictest.model.context.Frame; import org.cubictest.model.formElement.Option; import org.cubictest.model.formElement.Select; import com.thoughtworks.selenium.SeleniumException; /** * Class to convert transitions to selenium commands. * * @author chr_schwarz */ public class TransitionConverter implements ITransitionConverter<SeleniumHolder> { /** * Converts a user interactions transition to a list of Selenium commands. * * @param transition The transition to convert. */ public void handleUserInteractions(SeleniumHolder seleniumHolder, UserInteractionsTransition transition) { boolean needsPageReload = false; for (UserInteraction action : transition.getUserInteractions()) { IActionElement actionElement = action.getElement(); if (actionElement == null) { Logger.warn("Action element was null. Skipping user interaction: " + action); continue; } String commandName = handleUserInteraction(seleniumHolder, action); if (!commandName.equals(SeleniumUtils.FIREEVENT)) { needsPageReload = true; } //increment the number of steps in test: seleniumHolder.addResult(null, TestPartStatus.PASS); } if ((transition.getReloadsPage().equals(OnOffAutoTriState.AUTO) && needsPageReload) || (transition.getReloadsPage().equals(OnOffAutoTriState.ON))){ int timeout = SeleniumUtils.getTimeout(seleniumHolder.getSettings()); waitForPageToLoad(seleniumHolder, timeout); } else if (transition.getReloadsPage().equals(OnOffAutoTriState.OFF)) { try { Thread.sleep(transition.getSecondsToWaitForResult() * 1000); } catch (InterruptedException e) { Logger.warn("Interrupted while sleepting after user interaction"); } } } private void waitForPageToLoad(SeleniumHolder seleniumHolder, int seconds) { try { long millis = seconds * 1000; seleniumHolder.getSelenium().waitForPageToLoad(millis + ""); } catch (SeleniumException e) { ErrorHandler.logAndThrow("Selenium error while waiting for page to load. This may be due to an unsupported redirect. Timeout used: " + seconds + " seconds.\n\n" + "You might want try one of the experimental browser launchers (e.g. Firefox chrome or proxy injection mode)."); } } /** * Converts a single user interaction to a Selenium command. * @return the Selenium command name invoked. */ private String handleUserInteraction(SeleniumHolder seleniumHolder, UserInteraction userInteraction) { IActionElement element = userInteraction.getElement(); ActionType actionType = userInteraction.getActionType(); boolean withinFrame = false; if(element instanceof PageElement && seleniumHolder.isPageElementWithinFrame((PageElement)element)){ + //check if parent frame was found: + if (TestPartStatus.FAIL == seleniumHolder.getParentFrame((PageElement)element).getStatus()) { + ErrorHandler.logAndShowErrorDialogAndThrow("Cannot interact with element " + element + ":\n" + + "Parent frame " + seleniumHolder.getParentFrame((PageElement)element) + + " not found."); + } withinFrame = true; getToRightFrame(seleniumHolder, seleniumHolder.getParentFrame((PageElement) element)); } //Getting selenium commands, locators and values: String commandName = SeleniumUtils.getCommandName(actionType); String locator = null; String inputValue = null; if (element instanceof Option) { Select select = ((Option) element).getParent(); locator = "xpath=" + seleniumHolder.getFullContextWithAllElements(select); inputValue = SeleniumUtils.getOptionLocator((Option) element); }else { //all other elements if (element instanceof PageElement) { locator = "xpath=" + seleniumHolder.getFullContextWithAllElements((PageElement) element); } else if(element instanceof WebBrowser){ locator = userInteraction.getValue(); } else { throw new ExporterException("Unsupported action element type"); } inputValue = SeleniumUtils.getValue(userInteraction); } try { //invoke user interaction by reflection using command name from SeleniumUtil (legacy since Selenese exporter was written first): if (SeleniumUtils.hasSeleniumInputColumn(userInteraction)) { //two parameters seleniumHolder.getSelenium().execute(commandName, locator, inputValue); } else { //one parameter only seleniumHolder.getSelenium().execute(commandName, locator); } if(withinFrame && commandName.equals(SeleniumUtils.FIREEVENT)) upToParentFrame(seleniumHolder); return commandName; } catch (Exception e) { String msg = "Error invoking user interaction: " + userInteraction.toString() + "."; if (element instanceof PageElement) { PageElement pe = (PageElement) element; if (pe.getStatus().equals(TestPartStatus.FAIL)) { msg += "\n\nPage element " + pe.toString() + " not found."; } seleniumHolder.addResult(pe, TestPartStatus.EXCEPTION, pe.isNot()); } Logger.error(msg, e); throw new UserInteractionException(msg); } } private void getToRightFrame(SeleniumHolder seleniumHolder, PageElement element) { Frame parent = seleniumHolder.getParentFrame(element); if(parent != null){ getToRightFrame(seleniumHolder, parent); } String locator = "xpath=" + seleniumHolder.getFullContextWithAllElements(element); seleniumHolder.getSelenium().execute("selectFrame", locator); } private void upToParentFrame(SeleniumHolder seleniumHolder) { final CubicTestLocalRunner seleniumRunner = seleniumHolder.getSelenium(); seleniumRunner.execute("selectFrame", "relative=top"); } }
true
true
private String handleUserInteraction(SeleniumHolder seleniumHolder, UserInteraction userInteraction) { IActionElement element = userInteraction.getElement(); ActionType actionType = userInteraction.getActionType(); boolean withinFrame = false; if(element instanceof PageElement && seleniumHolder.isPageElementWithinFrame((PageElement)element)){ withinFrame = true; getToRightFrame(seleniumHolder, seleniumHolder.getParentFrame((PageElement) element)); } //Getting selenium commands, locators and values: String commandName = SeleniumUtils.getCommandName(actionType); String locator = null; String inputValue = null; if (element instanceof Option) { Select select = ((Option) element).getParent(); locator = "xpath=" + seleniumHolder.getFullContextWithAllElements(select); inputValue = SeleniumUtils.getOptionLocator((Option) element); }else { //all other elements if (element instanceof PageElement) { locator = "xpath=" + seleniumHolder.getFullContextWithAllElements((PageElement) element); } else if(element instanceof WebBrowser){ locator = userInteraction.getValue(); } else { throw new ExporterException("Unsupported action element type"); } inputValue = SeleniumUtils.getValue(userInteraction); } try { //invoke user interaction by reflection using command name from SeleniumUtil (legacy since Selenese exporter was written first): if (SeleniumUtils.hasSeleniumInputColumn(userInteraction)) { //two parameters seleniumHolder.getSelenium().execute(commandName, locator, inputValue); } else { //one parameter only seleniumHolder.getSelenium().execute(commandName, locator); } if(withinFrame && commandName.equals(SeleniumUtils.FIREEVENT)) upToParentFrame(seleniumHolder); return commandName; } catch (Exception e) { String msg = "Error invoking user interaction: " + userInteraction.toString() + "."; if (element instanceof PageElement) { PageElement pe = (PageElement) element; if (pe.getStatus().equals(TestPartStatus.FAIL)) { msg += "\n\nPage element " + pe.toString() + " not found."; } seleniumHolder.addResult(pe, TestPartStatus.EXCEPTION, pe.isNot()); } Logger.error(msg, e); throw new UserInteractionException(msg); } }
private String handleUserInteraction(SeleniumHolder seleniumHolder, UserInteraction userInteraction) { IActionElement element = userInteraction.getElement(); ActionType actionType = userInteraction.getActionType(); boolean withinFrame = false; if(element instanceof PageElement && seleniumHolder.isPageElementWithinFrame((PageElement)element)){ //check if parent frame was found: if (TestPartStatus.FAIL == seleniumHolder.getParentFrame((PageElement)element).getStatus()) { ErrorHandler.logAndShowErrorDialogAndThrow("Cannot interact with element " + element + ":\n" + "Parent frame " + seleniumHolder.getParentFrame((PageElement)element) + " not found."); } withinFrame = true; getToRightFrame(seleniumHolder, seleniumHolder.getParentFrame((PageElement) element)); } //Getting selenium commands, locators and values: String commandName = SeleniumUtils.getCommandName(actionType); String locator = null; String inputValue = null; if (element instanceof Option) { Select select = ((Option) element).getParent(); locator = "xpath=" + seleniumHolder.getFullContextWithAllElements(select); inputValue = SeleniumUtils.getOptionLocator((Option) element); }else { //all other elements if (element instanceof PageElement) { locator = "xpath=" + seleniumHolder.getFullContextWithAllElements((PageElement) element); } else if(element instanceof WebBrowser){ locator = userInteraction.getValue(); } else { throw new ExporterException("Unsupported action element type"); } inputValue = SeleniumUtils.getValue(userInteraction); } try { //invoke user interaction by reflection using command name from SeleniumUtil (legacy since Selenese exporter was written first): if (SeleniumUtils.hasSeleniumInputColumn(userInteraction)) { //two parameters seleniumHolder.getSelenium().execute(commandName, locator, inputValue); } else { //one parameter only seleniumHolder.getSelenium().execute(commandName, locator); } if(withinFrame && commandName.equals(SeleniumUtils.FIREEVENT)) upToParentFrame(seleniumHolder); return commandName; } catch (Exception e) { String msg = "Error invoking user interaction: " + userInteraction.toString() + "."; if (element instanceof PageElement) { PageElement pe = (PageElement) element; if (pe.getStatus().equals(TestPartStatus.FAIL)) { msg += "\n\nPage element " + pe.toString() + " not found."; } seleniumHolder.addResult(pe, TestPartStatus.EXCEPTION, pe.isNot()); } Logger.error(msg, e); throw new UserInteractionException(msg); } }
diff --git a/src/main/java/archimulator/sim/uncore/cache/partitioning/CPIBasedCachePartitioningHelper.java b/src/main/java/archimulator/sim/uncore/cache/partitioning/CPIBasedCachePartitioningHelper.java index 896e24be..f172ac4f 100644 --- a/src/main/java/archimulator/sim/uncore/cache/partitioning/CPIBasedCachePartitioningHelper.java +++ b/src/main/java/archimulator/sim/uncore/cache/partitioning/CPIBasedCachePartitioningHelper.java @@ -1,71 +1,71 @@ package archimulator.sim.uncore.cache.partitioning; import archimulator.sim.common.Simulation; import archimulator.sim.core.Thread; import archimulator.sim.core.event.InstructionCommittedEvent; import archimulator.sim.uncore.coherence.msi.controller.DirectoryController; import net.pickapack.action.Action1; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * CPI based cache partitioning helper. * * @author Min Cai */ public class CPIBasedCachePartitioningHelper extends CachePartitioningHelper { private Map<Integer, Long> committedInstructions; public CPIBasedCachePartitioningHelper(Simulation simulation) { this(simulation.getProcessor().getMemoryHierarchy().getL2CacheController()); } public CPIBasedCachePartitioningHelper(DirectoryController l2CacheController) { super(l2CacheController); this.committedInstructions = new TreeMap<Integer, Long>(); l2CacheController.getBlockingEventDispatcher().addListener(InstructionCommittedEvent.class, new Action1<InstructionCommittedEvent>() { public void apply(InstructionCommittedEvent event) { Thread thread = event.getDynamicInstruction().getThread(); if (!committedInstructions.containsKey(getThreadIdentifier(thread))) { committedInstructions.put(getThreadIdentifier(thread), 0L); } committedInstructions.put(getThreadIdentifier(thread), committedInstructions.get(getThreadIdentifier(thread)) + 1); } }); } @Override protected void newInterval() { List<Integer> partition = new ArrayList<Integer>(); List<Double> cyclePerInstructions = new ArrayList<Double>(); for(int threadId = 0; threadId < this.getNumThreads(); threadId++) { if (!committedInstructions.containsKey(threadId)) { committedInstructions.put(threadId, 0L); } long numCommittedInstructions = this.committedInstructions.get(threadId); cyclePerInstructions.add((double) this.getNumCyclesElapsedPerInterval() / numCommittedInstructions); } double cyclePerInstructionSum = 0; for(double cyclePerInstruction : cyclePerInstructions) { cyclePerInstructionSum += cyclePerInstruction; } for(int threadId = 0; threadId < this.getNumThreads(); threadId++) { - partition.add((int) (cyclePerInstructions.get(threadId) / cyclePerInstructionSum * this.getL2CacheController().getCache().getAssociativity())); + partition.add((int) (cyclePerInstructions.get(threadId) / cyclePerInstructionSum * (this.getL2CacheController().getCache().getAssociativity() - this.getNumThreads())) + 1); } this.setPartition(partition); this.committedInstructions.clear(); } }
true
true
protected void newInterval() { List<Integer> partition = new ArrayList<Integer>(); List<Double> cyclePerInstructions = new ArrayList<Double>(); for(int threadId = 0; threadId < this.getNumThreads(); threadId++) { if (!committedInstructions.containsKey(threadId)) { committedInstructions.put(threadId, 0L); } long numCommittedInstructions = this.committedInstructions.get(threadId); cyclePerInstructions.add((double) this.getNumCyclesElapsedPerInterval() / numCommittedInstructions); } double cyclePerInstructionSum = 0; for(double cyclePerInstruction : cyclePerInstructions) { cyclePerInstructionSum += cyclePerInstruction; } for(int threadId = 0; threadId < this.getNumThreads(); threadId++) { partition.add((int) (cyclePerInstructions.get(threadId) / cyclePerInstructionSum * this.getL2CacheController().getCache().getAssociativity())); } this.setPartition(partition); this.committedInstructions.clear(); }
protected void newInterval() { List<Integer> partition = new ArrayList<Integer>(); List<Double> cyclePerInstructions = new ArrayList<Double>(); for(int threadId = 0; threadId < this.getNumThreads(); threadId++) { if (!committedInstructions.containsKey(threadId)) { committedInstructions.put(threadId, 0L); } long numCommittedInstructions = this.committedInstructions.get(threadId); cyclePerInstructions.add((double) this.getNumCyclesElapsedPerInterval() / numCommittedInstructions); } double cyclePerInstructionSum = 0; for(double cyclePerInstruction : cyclePerInstructions) { cyclePerInstructionSum += cyclePerInstruction; } for(int threadId = 0; threadId < this.getNumThreads(); threadId++) { partition.add((int) (cyclePerInstructions.get(threadId) / cyclePerInstructionSum * (this.getL2CacheController().getCache().getAssociativity() - this.getNumThreads())) + 1); } this.setPartition(partition); this.committedInstructions.clear(); }
diff --git a/src/com/jmex/model/XMLparser/Converters/ObjToJme.java b/src/com/jmex/model/XMLparser/Converters/ObjToJme.java index 90b8ba347..914d0deb9 100755 --- a/src/com/jmex/model/XMLparser/Converters/ObjToJme.java +++ b/src/com/jmex/model/XMLparser/Converters/ObjToJme.java @@ -1,431 +1,431 @@ /* * Copyright (c) 2003-2005 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jmex.model.XMLparser.Converters; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import com.jme.image.Texture; import com.jme.math.Vector2f; import com.jme.math.Vector3f; import com.jme.renderer.ColorRGBA; import com.jme.renderer.Renderer; import com.jme.scene.Node; import com.jme.scene.Spatial; import com.jme.scene.TriMesh; import com.jme.scene.state.AlphaState; import com.jme.scene.state.MaterialState; import com.jme.scene.state.TextureState; import com.jme.system.DisplaySystem; import com.jme.util.geom.BufferUtils; import com.jmex.model.XMLparser.JmeBinaryWriter; /** * Started Date: Jul 17, 2004<br><br> * * Converts .obj files into .jme binary format. In order for ObjToJme to find the .mtl library, you must specify the * "mtllib" tag to the baseURL where the mtl libraries are to be found. Somewhat similar to this.setProperty("mtllib",objFile); * * @author Jack Lindamood */ public class ObjToJme extends FormatConverter{ private BufferedReader inFile; /** Every vertex in the file*/ private ArrayList vertexList=new ArrayList(); /** Every texture coordinate in the file*/ private ArrayList textureList=new ArrayList(); /** Every normal in the file*/ private ArrayList normalList=new ArrayList(); /** Last 'material' flag in the file*/ private MaterialGrouping curGroup; /** Default material group for groups without a material*/ private final MaterialGrouping DEFAULT_GROUP=new MaterialGrouping(); /** Maps material names to the actual material object **/ private HashMap materialNames=new HashMap(); /** Maps Materials to their vertex usage **/ private HashMap materialSets=new HashMap(); /** * Converts an Obj file to jME format. The syntax is: "ObjToJme file.obj outfile.jme". * @param args The array of parameters */ public static void main(String[] args){ new DummyDisplaySystem(); new ObjToJme().attemptFileConvert(args); } /** * Converts an .obj file to .jme format. If you wish to use a .mtl to load the obj's material information please specify * the base url where the .mtl is located with setProperty("mtllib",new URL(baseURL)) * @param format The .obj file's stream. * @param jMEFormat The .jme file's stream. * @throws IOException If anything bad happens. */ public void convert(InputStream format, OutputStream jMEFormat) throws IOException { vertexList.clear(); textureList.clear(); normalList.clear(); materialSets.clear(); materialNames.clear(); inFile=new BufferedReader(new InputStreamReader(format)); String in; curGroup=DEFAULT_GROUP; materialSets.put(DEFAULT_GROUP,new ArraySet()); while ((in=inFile.readLine())!=null){ processLine(in); } new JmeBinaryWriter().writeScene(buildStructure(),jMEFormat); nullAll(); } /** * Nulls all to let the gc do its job. * @throws IOException */ private void nullAll() throws IOException { vertexList.clear(); textureList.clear(); normalList.clear(); curGroup=null; materialSets.clear(); materialNames.clear(); inFile.close(); inFile=null; } /** * Converts the structures of the .obj file to a scene to write * @return The TriMesh or Node that represents the .obj file. */ private Spatial buildStructure() { Node toReturn=new Node("obj file"); Object[] o=materialSets.keySet().toArray(); for (int i=0;i<o.length;i++){ MaterialGrouping thisGroup=(MaterialGrouping) o[i]; ArraySet thisSet=(ArraySet) materialSets.get(thisGroup); if (thisSet.indexes.size()<3) continue; TriMesh thisMesh=new TriMesh("temp"+i); Vector3f[] vert=new Vector3f[thisSet.vertexes.size()]; Vector3f[] norm=new Vector3f[thisSet.vertexes.size()]; Vector2f[] text=new Vector2f[thisSet.vertexes.size()]; for (int j=0;j<thisSet.vertexes.size();j++){ vert[j]=(Vector3f) thisSet.vertexes.get(j); norm[j]=(Vector3f) thisSet.normals.get(j); text[j]=(Vector2f) thisSet.textures.get(j); } int[] indexes=new int[thisSet.indexes.size()]; for (int j=0;j<thisSet.indexes.size();j++) indexes[j]=((Integer)thisSet.indexes.get(j)).intValue(); thisMesh.reconstruct(BufferUtils.createFloatBuffer(vert), BufferUtils.createFloatBuffer(norm), null, BufferUtils.createFloatBuffer(text), BufferUtils.createIntBuffer(indexes)); if (properties.get("sillycolors")!=null) thisMesh.setRandomColors(); if (thisGroup.ts.isEnabled()) thisMesh.setRenderState(thisGroup.ts); thisMesh.setRenderState(thisGroup.m); if (thisGroup.as != null) { thisMesh.setRenderState(thisGroup.as); thisMesh.setRenderQueueMode(Renderer.QUEUE_TRANSPARENT); } toReturn.attachChild(thisMesh); } if (toReturn.getQuantity()==1) return toReturn.getChild(0); else return toReturn; } /** * Processes a line of text in the .obj file. * @param s The line of text in the file. * @throws IOException */ private void processLine(String s) throws IOException { if (s==null) return ; if (s.length()==0) return; String[] parts=s.split(" "); parts=removeEmpty(parts); if ("#".equals(parts[0])) return; if ("v".equals(parts[0])){ addVertextoList(parts); return; }else if ("vt".equals(parts[0])){ addTextoList(parts); return; } else if ("vn".equals(parts[0])){ addNormalToList(parts); return; } else if ("g".equals(parts[0])){ //see what the material name is if there isn't a name, assume its the default group if (parts.length >= 2 && materialNames.get(parts[1]) != null && materialNames.get(parts[1]) != null) curGroup = (MaterialGrouping) materialNames.get(parts[1]); else setDefaultGroup(); return; } else if ("f".equals(parts[0])){ addFaces(parts); return; } else if ("mtllib".equals(parts[0])){ loadMaterials(parts); return; } else if ("newmtl".equals(parts[0])){ addMaterial(parts); return; } else if ("usemtl".equals(parts[0])){ if (materialNames.get(parts[1])!=null) curGroup=(MaterialGrouping) materialNames.get(parts[1]); else setDefaultGroup(); return; } else if ("Ka".equals(parts[0])){ curGroup.m.setAmbient(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1)); return; } else if ("Kd".equals(parts[0])){ curGroup.m.setDiffuse(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1)); return; } else if ("Ks".equals(parts[0])){ curGroup.m.setSpecular(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1)); return; } else if ("Ns".equals(parts[0])){ curGroup.m.setShininess(Float.parseFloat(parts[1])); return; } else if ("d".equals(parts[0])){ curGroup.m.setAlpha(Float.parseFloat(parts[1])); ColorRGBA alpha = new ColorRGBA(1,1,1,curGroup.m.getAlpha()); curGroup.m.setAmbient(curGroup.m.getAmbient().mult(alpha)); curGroup.m.setDiffuse(curGroup.m.getDiffuse().mult(alpha)); curGroup.m.setSpecular(curGroup.m.getSpecular().mult(alpha)); if (curGroup.m.getAlpha() < 1.0f) curGroup.createAlphaState(); return; } else if ("map_d".equals(parts[0])) { curGroup.createAlphaState(); return; } else if ("map_Kd".equals(parts[0]) || "map_Ka".equals(parts[0])){ Texture t=new Texture(); - t.setImageLocation("file:/"+s.substring(6).trim()); + t.setImageLocation("file:/"+s.trim().substring(6)); curGroup.ts.setTexture(t); curGroup.ts.setEnabled(true); return; } } private String[] removeEmpty(String[] parts) { int cnt=0; for (int i=0;i<parts.length;i++){ if (!parts[i].equals("")) cnt++; } String[] toReturn=new String[cnt]; int index=0; for (int i=0;i<parts.length;i++){ if (!parts[i].equals("")){ toReturn[index++]=parts[i]; } } return toReturn; } private void addMaterial(String[] parts) { MaterialGrouping newMat=new MaterialGrouping(); materialNames.put(parts[1],newMat); materialSets.put(newMat,new ArraySet()); curGroup=newMat; } private void loadMaterials(String[] fileNames) throws IOException { URL matURL=(URL) properties.get("mtllib"); if (matURL==null) return; for (int i=1;i<fileNames.length;i++){ processMaterialFile(new URL(matURL,fileNames[i]).openStream()); } } private void processMaterialFile(InputStream inputStream) throws IOException { BufferedReader matFile=new BufferedReader(new InputStreamReader(inputStream)); String in; while ((in=matFile.readLine())!=null){ processLine(in); } } private void addFaces(String[] parts) { ArraySet thisMat=(ArraySet) materialSets.get(curGroup); IndexSet first=new IndexSet(parts[1]); int firstIndex=thisMat.findSet(first); IndexSet second=new IndexSet(parts[2]); int secondIndex=thisMat.findSet(second); IndexSet third=new IndexSet(); for (int i=3;i<parts.length;i++){ third.parseStringArray(parts[i]); thisMat.indexes.add(new Integer(firstIndex)); thisMat.indexes.add(new Integer(secondIndex)); int thirdIndex=thisMat.findSet(third); thisMat.indexes.add(new Integer(thirdIndex)); } } private void setDefaultGroup() { curGroup=DEFAULT_GROUP; } private void addNormalToList(String[] parts) { normalList.add(new Vector3f(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]))); } private void addTextoList(String[] parts) { if (parts.length==2) textureList.add(new Vector2f(Float.parseFloat(parts[1]),0)); else textureList.add(new Vector2f(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]))); } private void addVertextoList(String[] parts) { vertexList.add(new Vector3f(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]))); } private class MaterialGrouping{ public MaterialGrouping(){ m=DisplaySystem.getDisplaySystem().getRenderer().createMaterialState(); m.setAmbient(new ColorRGBA(.2f,.2f,.2f,1)); m.setDiffuse(new ColorRGBA(.8f,.8f,.8f,1)); m.setSpecular(ColorRGBA.white); m.setEnabled(true); ts=DisplaySystem.getDisplaySystem().getRenderer().createTextureState(); } public void createAlphaState() { if (as != null) return; as = DisplaySystem.getDisplaySystem().getRenderer() .createAlphaState(); as.setBlendEnabled(true); as.setSrcFunction(AlphaState.SB_SRC_ALPHA); as.setDstFunction(AlphaState.DB_ONE_MINUS_SRC_ALPHA); as.setTestEnabled(true); as.setTestFunction(AlphaState.TF_GREATER); as.setEnabled(true); } MaterialState m; TextureState ts; AlphaState as; } /** * Stores a complete set of vertex/texture/normal triplet set that is to be * indexed by the TriMesh. */ private class IndexSet{ public IndexSet(){} public IndexSet(String parts){ parseStringArray(parts); } public void parseStringArray(String parts){ int vIndex,nIndex,tIndex; String[] triplet=parts.split("/"); vIndex=Integer.parseInt(triplet[0]); if (vIndex<0){ vertex=(Vector3f) vertexList.get(vertexList.size()+vIndex); } else{ vertex=(Vector3f) vertexList.get(vIndex-1); // obj is 1 indexed } if (triplet.length < 2 || triplet[1]==null || triplet[1].equals("")){ texture=null; } else{ tIndex=Integer.parseInt(triplet[1]); if (tIndex<0){ texture=(Vector2f) textureList.get(textureList.size()+tIndex); } else{ texture=(Vector2f) textureList.get(tIndex-1); // obj is 1 indexed } } if (triplet.length!=3 || triplet[2]==null || triplet[2].equals("")){ normal=null; } else{ nIndex=Integer.parseInt(triplet[2]); if (nIndex<0){ normal=(Vector3f) normalList.get(normalList.size()+nIndex); } else{ normal=(Vector3f) normalList.get(nIndex-1); // obj is 1 indexed } } } Vector3f vertex; Vector2f texture; Vector3f normal; } /** * An array of information that will become a renderable trimesh. Each material has it's own trimesh. */ private class ArraySet{ private ArrayList vertexes=new ArrayList(); private ArrayList normals=new ArrayList(); private ArrayList textures=new ArrayList(); private ArrayList indexes=new ArrayList(); public int findSet(IndexSet v) { int i=0; for (i=0;i<normals.size();i++){ if (compareObjects(v.normal,normals.get(i)) && compareObjects(v.texture,textures.get(i)) && compareObjects(v.vertex,vertexes.get(i))) return i; } normals.add(v.normal); textures.add(v.texture); vertexes.add(v.vertex); return i; } private boolean compareObjects(Object o1, Object o2) { if (o1==null) return (o2==null); if (o2==null) return false; return o1.equals(o2); } } }
true
true
private void processLine(String s) throws IOException { if (s==null) return ; if (s.length()==0) return; String[] parts=s.split(" "); parts=removeEmpty(parts); if ("#".equals(parts[0])) return; if ("v".equals(parts[0])){ addVertextoList(parts); return; }else if ("vt".equals(parts[0])){ addTextoList(parts); return; } else if ("vn".equals(parts[0])){ addNormalToList(parts); return; } else if ("g".equals(parts[0])){ //see what the material name is if there isn't a name, assume its the default group if (parts.length >= 2 && materialNames.get(parts[1]) != null && materialNames.get(parts[1]) != null) curGroup = (MaterialGrouping) materialNames.get(parts[1]); else setDefaultGroup(); return; } else if ("f".equals(parts[0])){ addFaces(parts); return; } else if ("mtllib".equals(parts[0])){ loadMaterials(parts); return; } else if ("newmtl".equals(parts[0])){ addMaterial(parts); return; } else if ("usemtl".equals(parts[0])){ if (materialNames.get(parts[1])!=null) curGroup=(MaterialGrouping) materialNames.get(parts[1]); else setDefaultGroup(); return; } else if ("Ka".equals(parts[0])){ curGroup.m.setAmbient(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1)); return; } else if ("Kd".equals(parts[0])){ curGroup.m.setDiffuse(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1)); return; } else if ("Ks".equals(parts[0])){ curGroup.m.setSpecular(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1)); return; } else if ("Ns".equals(parts[0])){ curGroup.m.setShininess(Float.parseFloat(parts[1])); return; } else if ("d".equals(parts[0])){ curGroup.m.setAlpha(Float.parseFloat(parts[1])); ColorRGBA alpha = new ColorRGBA(1,1,1,curGroup.m.getAlpha()); curGroup.m.setAmbient(curGroup.m.getAmbient().mult(alpha)); curGroup.m.setDiffuse(curGroup.m.getDiffuse().mult(alpha)); curGroup.m.setSpecular(curGroup.m.getSpecular().mult(alpha)); if (curGroup.m.getAlpha() < 1.0f) curGroup.createAlphaState(); return; } else if ("map_d".equals(parts[0])) { curGroup.createAlphaState(); return; } else if ("map_Kd".equals(parts[0]) || "map_Ka".equals(parts[0])){ Texture t=new Texture(); t.setImageLocation("file:/"+s.substring(6).trim()); curGroup.ts.setTexture(t); curGroup.ts.setEnabled(true); return; } }
private void processLine(String s) throws IOException { if (s==null) return ; if (s.length()==0) return; String[] parts=s.split(" "); parts=removeEmpty(parts); if ("#".equals(parts[0])) return; if ("v".equals(parts[0])){ addVertextoList(parts); return; }else if ("vt".equals(parts[0])){ addTextoList(parts); return; } else if ("vn".equals(parts[0])){ addNormalToList(parts); return; } else if ("g".equals(parts[0])){ //see what the material name is if there isn't a name, assume its the default group if (parts.length >= 2 && materialNames.get(parts[1]) != null && materialNames.get(parts[1]) != null) curGroup = (MaterialGrouping) materialNames.get(parts[1]); else setDefaultGroup(); return; } else if ("f".equals(parts[0])){ addFaces(parts); return; } else if ("mtllib".equals(parts[0])){ loadMaterials(parts); return; } else if ("newmtl".equals(parts[0])){ addMaterial(parts); return; } else if ("usemtl".equals(parts[0])){ if (materialNames.get(parts[1])!=null) curGroup=(MaterialGrouping) materialNames.get(parts[1]); else setDefaultGroup(); return; } else if ("Ka".equals(parts[0])){ curGroup.m.setAmbient(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1)); return; } else if ("Kd".equals(parts[0])){ curGroup.m.setDiffuse(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1)); return; } else if ("Ks".equals(parts[0])){ curGroup.m.setSpecular(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1)); return; } else if ("Ns".equals(parts[0])){ curGroup.m.setShininess(Float.parseFloat(parts[1])); return; } else if ("d".equals(parts[0])){ curGroup.m.setAlpha(Float.parseFloat(parts[1])); ColorRGBA alpha = new ColorRGBA(1,1,1,curGroup.m.getAlpha()); curGroup.m.setAmbient(curGroup.m.getAmbient().mult(alpha)); curGroup.m.setDiffuse(curGroup.m.getDiffuse().mult(alpha)); curGroup.m.setSpecular(curGroup.m.getSpecular().mult(alpha)); if (curGroup.m.getAlpha() < 1.0f) curGroup.createAlphaState(); return; } else if ("map_d".equals(parts[0])) { curGroup.createAlphaState(); return; } else if ("map_Kd".equals(parts[0]) || "map_Ka".equals(parts[0])){ Texture t=new Texture(); t.setImageLocation("file:/"+s.trim().substring(6)); curGroup.ts.setTexture(t); curGroup.ts.setEnabled(true); return; } }
diff --git a/src/streamfish/Reg_ordre.java b/src/streamfish/Reg_ordre.java index ac02f89..8e217fb 100644 --- a/src/streamfish/Reg_ordre.java +++ b/src/streamfish/Reg_ordre.java @@ -1,501 +1,501 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package streamfish; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; /** * * @author Kristian */ public class Reg_ordre extends javax.swing.JPanel { private final int CUSTID; private GUI gui; private Menu[] menu; private CustomerAddress[] address; private Object[] addressPlus1; private Reg_ordre order = this; private DefaultComboBoxModel comboBox; private Customer customer; private Menu selMenu; private int antPers; private double priceReduction = 0; /** * Creates new form Reg_kunde */ public Reg_ordre(int custid, final GUI gui) { this.gui = gui; this.CUSTID = custid; this.customer = gui.getCustomer(CUSTID); menu = gui.getMenus(); address = gui.getAddress(CUSTID); addressPlus1 = new Object[address.length + 1]; priceReduction = customer.getPriceReduction(); for (int i = 0; i < address.length; i++) { addressPlus1[i] = address[i]; } addressPlus1[address.length] = new String("Add new address"); initComponents(); antPers = Integer.parseInt(jSpinner1.getValue().toString()); jLabel10.setText(priceReduction + " %"); jLabel7.setText(updatePrice() + ",-"); jLabel1.setText("Kundenr: " + CUSTID); updateMenu(); jSpinner1.addChangeListener(new ChangeListener(){ @Override public void stateChanged(ChangeEvent e) { antPers = Integer.parseInt(jSpinner1.getValue().toString()); jLabel7.setText(updatePrice() + ",-"); } }); comboBox = (DefaultComboBoxModel) jComboBox1.getModel(); for (Object addr : addressPlus1) { comboBox.addElement(addr); } jComboBox1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { javax.swing.JComboBox box = (javax.swing.JComboBox) e.getSource(); if (box.getSelectedItem() != null && box.getSelectedItem().getClass().equals(String.class)) { AddAddress address = new AddAddress(gui, CUSTID); address.addWindowListener(new WindowListener(){ @Override public void windowOpened(WindowEvent e) { } @Override public void windowClosing(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { order.updateAddress(); } @Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } }); } } }); } private double updatePrice(){ if(selMenu != null){ double price = selMenu.getPrice() * antPers * priceReduction; return price; } return 0; } private void updateAddress() { address = gui.getAddress(CUSTID); addressPlus1 = new Object[address.length + 1]; for (int i = 0; i < address.length; i++) { addressPlus1[i] = address[i]; } addressPlus1[address.length] = new String("Add new address"); comboBox.removeAllElements(); comboBox = (DefaultComboBoxModel) jComboBox1.getModel(); for (Object addr : addressPlus1) { comboBox.addElement(addr); } } private void updateMenu(){ menu = gui.getMenus(); if(menu!=null && menu.length > 0){ for (int i = 0; i < menu.length; i++) { DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); model.addRow(new Object[]{menu[i].getMenuName(), menu[i].getPrice(), menu[i].getDescription()}); } } jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener(){ public void valueChanged(ListSelectionEvent event) { int viewRow = jTable1.getSelectedRow(); if (!event.getValueIsAdjusting()) { try { selMenu = menu[viewRow]; } catch (Exception e) { } } } }); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jComboBox1 = new javax.swing.JComboBox(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jComboBox2 = new javax.swing.JComboBox(); jComboBox3 = new javax.swing.JComboBox(); jComboBox4 = new javax.swing.JComboBox(); jComboBox5 = new javax.swing.JComboBox(); jLabel6 = new javax.swing.JLabel(); jComboBox6 = new javax.swing.JComboBox(); jLabel3 = new javax.swing.JLabel(); jSpinner1 = new javax.swing.JSpinner(); jPanel2 = new javax.swing.JPanel(); jToggleButton1 = new javax.swing.JToggleButton(); jToggleButton2 = new javax.swing.JToggleButton(); jToggleButton3 = new javax.swing.JToggleButton(); jToggleButton4 = new javax.swing.JToggleButton(); jToggleButton5 = new javax.swing.JToggleButton(); jToggleButton6 = new javax.swing.JToggleButton(); jToggleButton7 = new javax.swing.JToggleButton(); jComboBox7 = new javax.swing.JComboBox(); jLabel11 = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jButton1.setText("Cancel"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Register"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel1.setText("Kundenr: " + CUSTID); jLabel4.setText("Select menu:"); jLabel5.setText("Address"); jComboBox1.setModel(new DefaultComboBoxModel()); jLabel7.setText("TODO" + ",-"); jLabel8.setText("Price:"); jLabel9.setText("Price reduction"); jLabel10.setText("TODO" + " %"); jLabel2.setText("Delivery date: (yyyy-mm-dd)"); jLabel2.setToolTipText(""); jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020" })); jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" })); jComboBox4.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" })); jComboBox5.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" })); jLabel6.setText("Time: (hh-mm)"); jLabel6.setToolTipText(""); jComboBox6.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "00", "15", "30", "45" })); jLabel3.setText("# Persons"); jSpinner1.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1))); jSpinner1.setValue(1); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jComboBox5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(jComboBox6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 27, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Normal order", jPanel1); jToggleButton1.setText("Mon"); jToggleButton2.setText("Tue"); jToggleButton3.setText("Wed"); jToggleButton4.setText("Thu"); jToggleButton5.setText("Fri"); jToggleButton6.setText("Sat"); jToggleButton7.setText("Sun"); jComboBox7.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1 Month", "3 Months", "6 Months", "1 Year" })); jLabel11.setText("Duration"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jComboBox7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jToggleButton1) .addGap(0, 0, 0) .addComponent(jToggleButton2) .addGap(0, 0, 0) .addComponent(jToggleButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(jToggleButton4) .addGap(0, 0, 0) .addComponent(jToggleButton5) .addGap(0, 0, 0) .addComponent(jToggleButton6) .addGap(0, 0, 0) .addComponent(jToggleButton7))) .addGap(10, 10, 10)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jToggleButton1) .addComponent(jToggleButton2) .addComponent(jToggleButton3) .addComponent(jToggleButton4) .addComponent(jToggleButton5) .addComponent(jToggleButton6) .addComponent(jToggleButton7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel11) .addComponent(jComboBox7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 7, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Subscription", jPanel2); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Name", "Price", "Description" } ) { boolean[] canEdit = new boolean [] { false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); - jTable1.setColumnSelectionAllowed(true); + jTable1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); + jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane2.setViewportView(jTable1); - jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jTable1.getColumnModel().getColumn(0).setMinWidth(50); jTable1.getColumnModel().getColumn(0).setPreferredWidth(175); jTable1.getColumnModel().getColumn(0).setMaxWidth(250); jTable1.getColumnModel().getColumn(1).setMinWidth(20); jTable1.getColumnModel().getColumn(1).setPreferredWidth(50); jTable1.getColumnModel().getColumn(1).setMaxWidth(50); jTable1.getColumnModel().getColumn(2).setResizable(false); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel9) .addComponent(jLabel8)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7) .addComponent(jLabel10, javax.swing.GroupLayout.Alignment.TRAILING))) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING)) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jTabbedPane1) .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4) .addGap(4, 4, 4) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(jLabel10)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(jLabel8)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2)) .addContainerGap()) ); jTabbedPane1.getAccessibleContext().setAccessibleName("Normal order"); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: gui.byttVindu(this, new MainMenu(gui)); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed antPers = Integer.parseInt(jSpinner1.getValue().toString()); String date = (String) jComboBox2.getSelectedItem() + "-" + (String) jComboBox3.getSelectedItem() + "-" + (String) jComboBox4.getSelectedItem(); String time = (String) jComboBox5.getSelectedItem() + ":" + (String) jComboBox6.getSelectedItem(); CustomerAddress orderAddress = (CustomerAddress) jComboBox1.getSelectedItem(); Order order = new Order(selMenu.getMenuId(), CUSTID, 1/*TODO?*/, antPers, date, time, orderAddress); gui.registerOrder(order); gui.byttVindu(this, new MainMenu(gui)); }//GEN-LAST:event_jButton2ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JComboBox jComboBox1; private javax.swing.JComboBox jComboBox2; private javax.swing.JComboBox jComboBox3; private javax.swing.JComboBox jComboBox4; private javax.swing.JComboBox jComboBox5; private javax.swing.JComboBox jComboBox6; private javax.swing.JComboBox jComboBox7; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSpinner jSpinner1; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTable jTable1; private javax.swing.JToggleButton jToggleButton1; private javax.swing.JToggleButton jToggleButton2; private javax.swing.JToggleButton jToggleButton3; private javax.swing.JToggleButton jToggleButton4; private javax.swing.JToggleButton jToggleButton5; private javax.swing.JToggleButton jToggleButton6; private javax.swing.JToggleButton jToggleButton7; // End of variables declaration//GEN-END:variables }
false
true
private void initComponents() { jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jComboBox1 = new javax.swing.JComboBox(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jComboBox2 = new javax.swing.JComboBox(); jComboBox3 = new javax.swing.JComboBox(); jComboBox4 = new javax.swing.JComboBox(); jComboBox5 = new javax.swing.JComboBox(); jLabel6 = new javax.swing.JLabel(); jComboBox6 = new javax.swing.JComboBox(); jLabel3 = new javax.swing.JLabel(); jSpinner1 = new javax.swing.JSpinner(); jPanel2 = new javax.swing.JPanel(); jToggleButton1 = new javax.swing.JToggleButton(); jToggleButton2 = new javax.swing.JToggleButton(); jToggleButton3 = new javax.swing.JToggleButton(); jToggleButton4 = new javax.swing.JToggleButton(); jToggleButton5 = new javax.swing.JToggleButton(); jToggleButton6 = new javax.swing.JToggleButton(); jToggleButton7 = new javax.swing.JToggleButton(); jComboBox7 = new javax.swing.JComboBox(); jLabel11 = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jButton1.setText("Cancel"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Register"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel1.setText("Kundenr: " + CUSTID); jLabel4.setText("Select menu:"); jLabel5.setText("Address"); jComboBox1.setModel(new DefaultComboBoxModel()); jLabel7.setText("TODO" + ",-"); jLabel8.setText("Price:"); jLabel9.setText("Price reduction"); jLabel10.setText("TODO" + " %"); jLabel2.setText("Delivery date: (yyyy-mm-dd)"); jLabel2.setToolTipText(""); jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020" })); jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" })); jComboBox4.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" })); jComboBox5.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" })); jLabel6.setText("Time: (hh-mm)"); jLabel6.setToolTipText(""); jComboBox6.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "00", "15", "30", "45" })); jLabel3.setText("# Persons"); jSpinner1.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1))); jSpinner1.setValue(1); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jComboBox5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(jComboBox6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 27, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Normal order", jPanel1); jToggleButton1.setText("Mon"); jToggleButton2.setText("Tue"); jToggleButton3.setText("Wed"); jToggleButton4.setText("Thu"); jToggleButton5.setText("Fri"); jToggleButton6.setText("Sat"); jToggleButton7.setText("Sun"); jComboBox7.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1 Month", "3 Months", "6 Months", "1 Year" })); jLabel11.setText("Duration"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jComboBox7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jToggleButton1) .addGap(0, 0, 0) .addComponent(jToggleButton2) .addGap(0, 0, 0) .addComponent(jToggleButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(jToggleButton4) .addGap(0, 0, 0) .addComponent(jToggleButton5) .addGap(0, 0, 0) .addComponent(jToggleButton6) .addGap(0, 0, 0) .addComponent(jToggleButton7))) .addGap(10, 10, 10)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jToggleButton1) .addComponent(jToggleButton2) .addComponent(jToggleButton3) .addComponent(jToggleButton4) .addComponent(jToggleButton5) .addComponent(jToggleButton6) .addComponent(jToggleButton7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel11) .addComponent(jComboBox7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 7, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Subscription", jPanel2); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Name", "Price", "Description" } ) { boolean[] canEdit = new boolean [] { false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jTable1.setColumnSelectionAllowed(true); jScrollPane2.setViewportView(jTable1); jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jTable1.getColumnModel().getColumn(0).setMinWidth(50); jTable1.getColumnModel().getColumn(0).setPreferredWidth(175); jTable1.getColumnModel().getColumn(0).setMaxWidth(250); jTable1.getColumnModel().getColumn(1).setMinWidth(20); jTable1.getColumnModel().getColumn(1).setPreferredWidth(50); jTable1.getColumnModel().getColumn(1).setMaxWidth(50); jTable1.getColumnModel().getColumn(2).setResizable(false); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel9) .addComponent(jLabel8)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7) .addComponent(jLabel10, javax.swing.GroupLayout.Alignment.TRAILING))) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING)) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jTabbedPane1) .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4) .addGap(4, 4, 4) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(jLabel10)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(jLabel8)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2)) .addContainerGap()) ); jTabbedPane1.getAccessibleContext().setAccessibleName("Normal order"); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jComboBox1 = new javax.swing.JComboBox(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jComboBox2 = new javax.swing.JComboBox(); jComboBox3 = new javax.swing.JComboBox(); jComboBox4 = new javax.swing.JComboBox(); jComboBox5 = new javax.swing.JComboBox(); jLabel6 = new javax.swing.JLabel(); jComboBox6 = new javax.swing.JComboBox(); jLabel3 = new javax.swing.JLabel(); jSpinner1 = new javax.swing.JSpinner(); jPanel2 = new javax.swing.JPanel(); jToggleButton1 = new javax.swing.JToggleButton(); jToggleButton2 = new javax.swing.JToggleButton(); jToggleButton3 = new javax.swing.JToggleButton(); jToggleButton4 = new javax.swing.JToggleButton(); jToggleButton5 = new javax.swing.JToggleButton(); jToggleButton6 = new javax.swing.JToggleButton(); jToggleButton7 = new javax.swing.JToggleButton(); jComboBox7 = new javax.swing.JComboBox(); jLabel11 = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jButton1.setText("Cancel"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Register"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel1.setText("Kundenr: " + CUSTID); jLabel4.setText("Select menu:"); jLabel5.setText("Address"); jComboBox1.setModel(new DefaultComboBoxModel()); jLabel7.setText("TODO" + ",-"); jLabel8.setText("Price:"); jLabel9.setText("Price reduction"); jLabel10.setText("TODO" + " %"); jLabel2.setText("Delivery date: (yyyy-mm-dd)"); jLabel2.setToolTipText(""); jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020" })); jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" })); jComboBox4.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" })); jComboBox5.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" })); jLabel6.setText("Time: (hh-mm)"); jLabel6.setToolTipText(""); jComboBox6.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "00", "15", "30", "45" })); jLabel3.setText("# Persons"); jSpinner1.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1))); jSpinner1.setValue(1); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jComboBox5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(jComboBox6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 27, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Normal order", jPanel1); jToggleButton1.setText("Mon"); jToggleButton2.setText("Tue"); jToggleButton3.setText("Wed"); jToggleButton4.setText("Thu"); jToggleButton5.setText("Fri"); jToggleButton6.setText("Sat"); jToggleButton7.setText("Sun"); jComboBox7.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1 Month", "3 Months", "6 Months", "1 Year" })); jLabel11.setText("Duration"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jComboBox7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jToggleButton1) .addGap(0, 0, 0) .addComponent(jToggleButton2) .addGap(0, 0, 0) .addComponent(jToggleButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(jToggleButton4) .addGap(0, 0, 0) .addComponent(jToggleButton5) .addGap(0, 0, 0) .addComponent(jToggleButton6) .addGap(0, 0, 0) .addComponent(jToggleButton7))) .addGap(10, 10, 10)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jToggleButton1) .addComponent(jToggleButton2) .addComponent(jToggleButton3) .addComponent(jToggleButton4) .addComponent(jToggleButton5) .addComponent(jToggleButton6) .addComponent(jToggleButton7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel11) .addComponent(jComboBox7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 7, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Subscription", jPanel2); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Name", "Price", "Description" } ) { boolean[] canEdit = new boolean [] { false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jTable1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane2.setViewportView(jTable1); jTable1.getColumnModel().getColumn(0).setMinWidth(50); jTable1.getColumnModel().getColumn(0).setPreferredWidth(175); jTable1.getColumnModel().getColumn(0).setMaxWidth(250); jTable1.getColumnModel().getColumn(1).setMinWidth(20); jTable1.getColumnModel().getColumn(1).setPreferredWidth(50); jTable1.getColumnModel().getColumn(1).setMaxWidth(50); jTable1.getColumnModel().getColumn(2).setResizable(false); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel9) .addComponent(jLabel8)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7) .addComponent(jLabel10, javax.swing.GroupLayout.Alignment.TRAILING))) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING)) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jTabbedPane1) .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4) .addGap(4, 4, 4) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(jLabel10)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(jLabel8)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2)) .addContainerGap()) ); jTabbedPane1.getAccessibleContext().setAccessibleName("Normal order"); }// </editor-fold>//GEN-END:initComponents
diff --git a/Aoag/src/com/turlutu/Bonus.java b/Aoag/src/com/turlutu/Bonus.java index f1396af..9c4d717 100644 --- a/Aoag/src/com/turlutu/Bonus.java +++ b/Aoag/src/com/turlutu/Bonus.java @@ -1,108 +1,108 @@ package com.turlutu; import javax.microedition.khronos.opengles.GL10; import android.util.Log; import com.android.angle.AnglePhysicObject; import com.android.angle.AngleSound; import com.android.angle.AngleSprite; /** * extends AnglePhysicObject * * @author Matthieu * */ class Bonus extends AnglePhysicObject { protected boolean mUsed; protected float mRadius; protected enum TypeBonus { NONE, // 0 ADDSCORE,// 1=> GameUI.setBonus(..) MOREJUMP, // 2 => Ball.jump() LESSJUMP, // 3 => Ball.jump() CHANGEPHYSICS, // 4 => MainActivity.onSensorChange() & GameUI.onTcouhEvent DISABLECHANGECOLOR, // 5 => Ball.changeColorLeft/Right() ALLPLATEFORME}; // 6 => MyPhysicsEngine.kynetics() private GameUI mGame; private AngleSound sndTouch; private boolean mustdraw = true; private AngleSprite mSprite; private int mType; static int radius = 8; static int nbtype = 6; static TypeBonus[] mapTypeBonus = { TypeBonus.NONE, // 0 TypeBonus.ADDSCORE, // 1 TypeBonus.MOREJUMP, // 2 TypeBonus.LESSJUMP, // 3 TypeBonus.CHANGEPHYSICS, // 4 TypeBonus.DISABLECHANGECOLOR, // 5 TypeBonus.ALLPLATEFORME};// 6 static float[] timesActionBonus = { 0, // 0 0, // 1 4, // 2 4, // 3 4, // 4 4, // 5 6}; // 6 public Bonus(GameUI game) { super(0, 1); mGame = game; mUsed = false; - mType = (int) (Math.random() * (nbtype)); + mType = (int) (Math.random() * (nbtype)) + 1; sndTouch = mGame.sndBonus[mType]; mSprite=new AngleSprite(mGame.mBonusLayout[mType]); addCircleCollider(new BallCollider(0, 0, radius)); } /** * @return surface */ @Override public float getSurface() { return (float) (mRadius * mRadius * 3.14); } /** * Draw the sprite and/or colliders * * @param gl */ @Override public void draw(GL10 gl) { if(mustdraw) { mSprite.mPosition.set(mPosition); mSprite.draw(gl); drawColliders(gl,1f,0f,0f); } } public BallCollider collider() { return (BallCollider) mCircleColliders[0]; } protected void onDie() { if (mUsed) { Log.i("Bonus", "Bonus onDie debut"); Log.i("Bonus", "TypeBonus : "+mapTypeBonus[mType]); mGame.setBonus(mapTypeBonus[mType],timesActionBonus[mType]); sndTouch.play(1,false); Log.i("Bonus", "Bonus onDie fin"); } } };
true
true
public Bonus(GameUI game) { super(0, 1); mGame = game; mUsed = false; mType = (int) (Math.random() * (nbtype)); sndTouch = mGame.sndBonus[mType]; mSprite=new AngleSprite(mGame.mBonusLayout[mType]); addCircleCollider(new BallCollider(0, 0, radius)); }
public Bonus(GameUI game) { super(0, 1); mGame = game; mUsed = false; mType = (int) (Math.random() * (nbtype)) + 1; sndTouch = mGame.sndBonus[mType]; mSprite=new AngleSprite(mGame.mBonusLayout[mType]); addCircleCollider(new BallCollider(0, 0, radius)); }
diff --git a/src/main/java/com/github/anba/es6draft/runtime/objects/ArrayPrototype.java b/src/main/java/com/github/anba/es6draft/runtime/objects/ArrayPrototype.java index ca223b46..35f26881 100755 --- a/src/main/java/com/github/anba/es6draft/runtime/objects/ArrayPrototype.java +++ b/src/main/java/com/github/anba/es6draft/runtime/objects/ArrayPrototype.java @@ -1,912 +1,919 @@ /** * Copyright (c) 2012-2013 André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ package com.github.anba.es6draft.runtime.objects; import static com.github.anba.es6draft.runtime.AbstractOperations.*; import static com.github.anba.es6draft.runtime.internal.Errors.throwTypeError; import static com.github.anba.es6draft.runtime.internal.Properties.createProperties; import static com.github.anba.es6draft.runtime.internal.ScriptRuntime.strictEqualityComparison; import static com.github.anba.es6draft.runtime.objects.ArrayIteratorPrototype.CreateArrayIterator; import static com.github.anba.es6draft.runtime.types.Undefined.UNDEFINED; import static com.github.anba.es6draft.runtime.types.builtins.ExoticArray.ArrayCreate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.github.anba.es6draft.runtime.ExecutionContext; import com.github.anba.es6draft.runtime.Realm; import com.github.anba.es6draft.runtime.internal.Initialisable; import com.github.anba.es6draft.runtime.internal.Messages; import com.github.anba.es6draft.runtime.internal.Properties.Function; import com.github.anba.es6draft.runtime.internal.Properties.Optional; import com.github.anba.es6draft.runtime.internal.Properties.Prototype; import com.github.anba.es6draft.runtime.internal.Properties.Value; import com.github.anba.es6draft.runtime.objects.ArrayIteratorPrototype.ArrayIterationKind; import com.github.anba.es6draft.runtime.types.BuiltinSymbol; import com.github.anba.es6draft.runtime.types.Callable; import com.github.anba.es6draft.runtime.types.Intrinsics; import com.github.anba.es6draft.runtime.types.PropertyDescriptor; import com.github.anba.es6draft.runtime.types.ScriptObject; import com.github.anba.es6draft.runtime.types.Type; import com.github.anba.es6draft.runtime.types.builtins.ExoticArray; import com.github.anba.es6draft.runtime.types.builtins.OrdinaryObject; /** * <h1>15 Standard Built-in ECMAScript Objects</h1><br> * <h2>15.4 Array Objects</h2> * <ul> * <li>15.4.4 Properties of the Array Prototype Object * <li>15.4.5 Properties of Array Instances * </ul> */ public class ArrayPrototype extends OrdinaryObject implements Initialisable { public ArrayPrototype(Realm realm) { super(realm); } @Override public void initialise(ExecutionContext cx) { createProperties(this, cx, Properties.class); // 15.4.4.26 Array.prototype.@@iterator ( ) defineOwnProperty(cx, BuiltinSymbol.iterator.get(), new PropertyDescriptor(Get(cx, this, "values"), true, false, true)); } /** * 15.4.4 Properties of the Array Prototype Object */ public enum Properties { ; @Prototype public static final Intrinsics __proto__ = Intrinsics.ObjectPrototype; /** * 15.4.4.1 Array.prototype.constructor */ @Value(name = "constructor") public static final Intrinsics constructor = Intrinsics.Array; /** * 15.4.4.2 Array.prototype.toString ( ) */ @Function(name = "toString", arity = 0) public static Object toString(ExecutionContext cx, Object thisValue) { ScriptObject array = ToObject(cx, thisValue); Object func = Get(cx, array, "join"); if (!IsCallable(func)) { func = cx.getIntrinsic(Intrinsics.ObjProto_toString); } return ((Callable) func).call(cx, array); } /** * 15.4.4.3 Array.prototype.toLocaleString ( ) */ @Function(name = "toLocaleString", arity = 0) public static Object toLocaleString(ExecutionContext cx, Object thisValue) { ScriptObject array = ToObject(cx, thisValue); Object arrayLen = Get(cx, array, "length"); long len = ToUint32(cx, arrayLen); String separator = ","; if (len == 0) { return ""; } StringBuilder r = new StringBuilder(); Object firstElement = Get(cx, array, "0"); if (Type.isUndefinedOrNull(firstElement)) { r.append(""); } else { r.append(ToString(cx, Invoke(cx, firstElement, "toLocaleString"))); } for (long k = 1; k < len; ++k) { Object nextElement = Get(cx, array, ToString(k)); if (Type.isUndefinedOrNull(nextElement)) { r.append(separator).append(""); } else { r.append(separator).append( ToString(cx, Invoke(cx, nextElement, "toLocaleString"))); } } return r.toString(); } /** * 15.4.4.4 Array.prototype.concat ( [ item1 [ , item2 [ , ... ] ] ] ) */ @Function(name = "concat", arity = 1) public static Object concat(ExecutionContext cx, Object thisValue, Object... items) { ScriptObject o = ToObject(cx, thisValue); ScriptObject a = ArrayCreate(cx, 0); long n = 0; int itemsLength = items.length; items = Arrays.copyOf(items, itemsLength + 1, Object[].class); System.arraycopy(items, 0, items, 1, itemsLength); items[0] = o; for (Object item : items) { if (item instanceof ExoticArray) { assert item instanceof ScriptObject; ScriptObject e = (ScriptObject) item; long len = ToUint32(cx, Get(cx, e, "length")); for (long k = 0; k < len; ++k, ++n) { String p = ToString(k); boolean exists = HasProperty(cx, e, p); if (exists) { Object subElement = Get(cx, e, p); a.defineOwnProperty(cx, ToString(n), new PropertyDescriptor(subElement, true, true, true)); } } } else { a.defineOwnProperty(cx, ToString(n++), new PropertyDescriptor(item, true, true, true)); } } Put(cx, a, "length", n, true); return a; } /** * 15.4.4.5 Array.prototype.join (separator) */ @Function(name = "join", arity = 1) public static Object join(ExecutionContext cx, Object thisValue, Object separator) { ScriptObject o = ToObject(cx, thisValue); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); if (Type.isUndefined(separator)) { separator = ","; } String sep = ToFlatString(cx, separator); if (len == 0) { return ""; } StringBuilder r = new StringBuilder(); Object element0 = Get(cx, o, "0"); if (Type.isUndefinedOrNull(element0)) { r.append(""); } else { r.append(ToString(cx, element0)); } for (long k = 1; k < len; ++k) { Object element = Get(cx, o, ToString(k)); if (Type.isUndefinedOrNull(element)) { r.append(sep).append(""); } else { r.append(sep).append(ToString(cx, element)); } } return r.toString(); } /** * 15.4.4.6 Array.prototype.pop ( ) */ @Function(name = "pop", arity = 0) public static Object pop(ExecutionContext cx, Object thisValue) { ScriptObject o = ToObject(cx, thisValue); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); if (len == 0) { Put(cx, o, "length", 0, true); return UNDEFINED; } else { assert len > 0; long newLen = len - 1; String index = ToString(newLen); Object element = Get(cx, o, index); DeletePropertyOrThrow(cx, o, index); Put(cx, o, "length", newLen, true); return element; } } /** * 15.4.4.7 Array.prototype.push ( [ item1 [ , item2 [ , ... ] ] ] ) */ @Function(name = "push", arity = 1) public static Object push(ExecutionContext cx, Object thisValue, Object... items) { ScriptObject o = ToObject(cx, thisValue); Object lenVal = Get(cx, o, "length"); long n = ToUint32(cx, lenVal); for (Object e : items) { Put(cx, o, ToString(n), e, true); n += 1; } Put(cx, o, "length", n, true); return n; } /** * 15.4.4.8 Array.prototype.reverse ( ) */ @Function(name = "reverse", arity = 0) public static Object reverse(ExecutionContext cx, Object thisValue) { ScriptObject o = ToObject(cx, thisValue); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); long middle = len / 2L; for (long lower = 0; lower != middle; ++lower) { long upper = len - lower - 1; String upperP = ToString(upper); String lowerP = ToString(lower); Object lowerValue = Get(cx, o, lowerP); Object upperValue = Get(cx, o, upperP); boolean lowerExists = HasProperty(cx, o, lowerP); boolean upperExists = HasProperty(cx, o, upperP); if (lowerExists && upperExists) { Put(cx, o, lowerP, upperValue, true); Put(cx, o, upperP, lowerValue, true); } else if (!lowerExists && upperExists) { Put(cx, o, lowerP, upperValue, true); DeletePropertyOrThrow(cx, o, upperP); } else if (lowerExists && !upperExists) { DeletePropertyOrThrow(cx, o, lowerP); Put(cx, o, upperP, lowerValue, true); } else { // no action required } } return o; } /** * 15.4.4.9 Array.prototype.shift ( ) */ @Function(name = "shift", arity = 0) public static Object shift(ExecutionContext cx, Object thisValue) { ScriptObject o = ToObject(cx, thisValue); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); if (len == 0) { Put(cx, o, "length", 0, true); return UNDEFINED; } Object first = Get(cx, o, "0"); for (long k = 1; k < len; ++k) { String from = ToString(k); String to = ToString(k - 1); boolean fromPresent = HasProperty(cx, o, from); if (fromPresent) { Object fromVal = Get(cx, o, from); Put(cx, o, to, fromVal, true); } else { DeletePropertyOrThrow(cx, o, to); } } DeletePropertyOrThrow(cx, o, ToString(len - 1)); Put(cx, o, "length", len - 1, true); return first; } /** * 15.4.4.10 Array.prototype.slice (start, end) */ @Function(name = "slice", arity = 2) public static Object slice(ExecutionContext cx, Object thisValue, Object start, Object end) { ScriptObject o = ToObject(cx, thisValue); ScriptObject a = ArrayCreate(cx, 0); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); double relativeStart = ToInteger(cx, start); long k; if (relativeStart < 0) { k = (long) Math.max(len + relativeStart, 0); } else { k = (long) Math.min(relativeStart, len); } double relativeEnd; if (Type.isUndefined(end)) { relativeEnd = len; } else { relativeEnd = ToInteger(cx, end); } long finall; if (relativeEnd < 0) { finall = (long) Math.max(len + relativeEnd, 0); } else { finall = (long) Math.min(relativeEnd, len); } long n = 0; for (; k < finall; ++k, ++n) { String pk = ToString(k); boolean kpresent = HasProperty(cx, o, pk); if (kpresent) { Object kvalue = Get(cx, o, pk); String p = ToString(n); boolean status = CreateOwnDataProperty(cx, a, p, kvalue); if (!status) { // FIXME: spec bug? (Assert instead of throw TypeError?) (Bug 1402) throw throwTypeError(cx, Messages.Key.PropertyNotCreatable, p); } } } // FIXME: spec bug (call to Put does make sense with the supplied args) (Bug 1402) Put(cx, a, "length", n, true); return a; } private static class DefaultComparator implements Comparator<Object> { private final ExecutionContext cx; DefaultComparator(ExecutionContext cx) { this.cx = cx; } @Override public int compare(Object o1, Object o2) { String x = ToFlatString(cx, o1); String y = ToFlatString(cx, o2); return x.compareTo(y); } } private static class FunctionComparator implements Comparator<Object> { private final ExecutionContext cx; private final Callable comparefn; FunctionComparator(ExecutionContext cx, Callable comparefn) { this.cx = cx; this.comparefn = comparefn; } @Override public int compare(Object o1, Object o2) { double c = ToInteger(cx, comparefn.call(cx, UNDEFINED, o1, o2)); return (c == 0 ? 0 : c < 0 ? -1 : 1); } } /** * 15.4.4.11 Array.prototype.sort (comparefn) */ @Function(name = "sort", arity = 1) public static Object sort(ExecutionContext cx, Object thisValue, Object comparefn) { ScriptObject obj = ToObject(cx, thisValue); long len = ToUint32(cx, Get(cx, obj, "length")); int emptyCount = 0; int undefCount = 0; List<Object> elements = new ArrayList<>((int) Math.min(len, 1024)); for (int i = 0; i < len; ++i) { String index = ToString(i); if (HasProperty(cx, obj, index)) { Object e = Get(cx, obj, index); if (!Type.isUndefined(e)) { elements.add(e); } else { undefCount += 1; } } else { emptyCount += 1; } } int count = elements.size(); if (count > 1) { Comparator<Object> comparator; if (!Type.isUndefined(comparefn)) { if (!IsCallable(comparefn)) { throw throwTypeError(cx, Messages.Key.NotCallable); } comparator = new FunctionComparator(cx, (Callable) comparefn); } else { comparator = new DefaultComparator(cx); } Collections.sort(elements, comparator); } for (int i = 0, offset = 0; i < count; ++i) { String p = ToString(offset + i); Put(cx, obj, p, elements.get(i), true); } for (int i = 0, offset = count; i < undefCount; ++i) { String p = ToString(offset + i); Put(cx, obj, p, UNDEFINED, true); } for (int i = 0, offset = count + undefCount; i < emptyCount; ++i) { DeletePropertyOrThrow(cx, obj, ToString(offset + i)); } return obj; } /** * 15.4.4.12 Array.prototype.splice (start, deleteCount [ , item1 [ , item2 [ , ... ] ] ] ) */ @Function(name = "splice", arity = 2) - public static Object splice(ExecutionContext cx, Object thisValue, Object start, - Object deleteCount, Object... items) { + public static Object splice(ExecutionContext cx, Object thisValue, + @Optional(Optional.Default.NONE) Object start, + @Optional(Optional.Default.NONE) Object deleteCount, Object... items) { ScriptObject o = ToObject(cx, thisValue); ScriptObject a = ArrayCreate(cx, 0); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); - double relativeStart = ToInteger(cx, start); + double relativeStart = (start != null ? ToInteger(cx, start) : 0); long actualStart; if (relativeStart < 0) { actualStart = (long) Math.max(len + relativeStart, 0); } else { actualStart = (long) Math.min(relativeStart, len); } - long actualDeleteCount = (long) Math.min(Math.max(ToInteger(cx, deleteCount), 0), len - - actualStart); + // TODO: track spec, https://bugs.ecmascript.org/show_bug.cgi?id=429 + long actualDeleteCount; + if (start != null && deleteCount == null) { + actualDeleteCount = (len - actualStart); + } else { + double del = (deleteCount != null ? Math.max(ToInteger(cx, deleteCount), 0) : 0); + actualDeleteCount = (long) Math.min(del, len - actualStart); + } for (long k = 0; k < actualDeleteCount; ++k) { String from = ToString(actualStart + k); boolean fromPresent = HasProperty(cx, o, from); if (fromPresent) { Object fromValue = Get(cx, o, from); a.defineOwnProperty(cx, ToString(k), new PropertyDescriptor(fromValue, true, true, true)); } } Put(cx, a, "length", actualDeleteCount, true); int itemCount = items.length; if (itemCount < actualDeleteCount) { for (long k = actualStart; k < (len - actualDeleteCount); ++k) { String from = ToString(k + actualDeleteCount); String to = ToString(k + itemCount); boolean fromPresent = HasProperty(cx, o, from); if (fromPresent) { Object fromValue = Get(cx, o, from); Put(cx, o, to, fromValue, true); } else { DeletePropertyOrThrow(cx, o, to); } } for (long k = len; k > (len - actualDeleteCount + itemCount); --k) { DeletePropertyOrThrow(cx, o, ToString(k - 1)); } } else if (itemCount > actualDeleteCount) { for (long k = (len - actualDeleteCount); k > actualStart; --k) { String from = ToString(k + actualDeleteCount - 1); String to = ToString(k + itemCount - 1); boolean fromPresent = HasProperty(cx, o, from); if (fromPresent) { Object fromValue = Get(cx, o, from); Put(cx, o, to, fromValue, true); } else { DeletePropertyOrThrow(cx, o, to); } } } long k = actualStart; for (int i = 0; i < itemCount; ++k, ++i) { Object e = items[i]; Put(cx, o, ToString(k), e, true); } Put(cx, o, "length", len - actualDeleteCount + itemCount, true); return a; } /** * 15.4.4.13 Array.prototype.unshift ( [ item1 [ , item2 [ , ... ] ] ] ) */ @Function(name = "unshift", arity = 1) public static Object unshift(ExecutionContext cx, Object thisValue, Object... items) { ScriptObject o = ToObject(cx, thisValue); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); int argCount = items.length; for (long k = len; k > 0; --k) { String from = ToString(k - 1); String to = ToString(k + argCount - 1); boolean fromPresent = HasProperty(cx, o, from); if (fromPresent) { Object fromValue = Get(cx, o, from); Put(cx, o, to, fromValue, true); } else { DeletePropertyOrThrow(cx, o, to); } } for (int j = 0; j < items.length; ++j) { Object e = items[j]; Put(cx, o, ToString(j), e, true); } Put(cx, o, "length", len + argCount, true); return len + argCount; } /** * 15.4.4.14 Array.prototype.indexOf ( searchElement [ , fromIndex ] ) */ @Function(name = "indexOf", arity = 1) public static Object indexOf(ExecutionContext cx, Object thisValue, Object searchElement, @Optional(Optional.Default.NONE) Object fromIndex) { ScriptObject o = ToObject(cx, thisValue); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); if (len == 0) { return -1; } long n; if (fromIndex != null) { n = (long) ToInteger(cx, fromIndex); } else { n = 0; } if (n >= len) { return -1; } long k; if (n >= 0) { k = n; } else { k = (long) (len - Math.abs(n)); if (k < 0) { k = 0; } } for (; k < len; ++k) { String pk = ToString(k); boolean kpresent = HasProperty(cx, o, pk); if (kpresent) { Object elementk = Get(cx, o, pk); boolean same = strictEqualityComparison(searchElement, elementk); if (same) { return k; } } } return -1; } /** * 15.4.4.15 Array.prototype.lastIndexOf ( searchElement [ , fromIndex ] ) */ @Function(name = "lastIndexOf", arity = 1) public static Object lastIndexOf(ExecutionContext cx, Object thisValue, Object searchElement, @Optional(Optional.Default.NONE) Object fromIndex) { ScriptObject o = ToObject(cx, thisValue); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); if (len == 0) { return -1; } long n; if (fromIndex != null) { n = (long) ToInteger(cx, fromIndex); } else { n = (long) (len - 1); } long k; if (n >= 0) { k = (long) Math.min(n, len - 1); } else { k = (long) (len - Math.abs(n)); } for (; k >= 0; --k) { String pk = ToString(k); boolean kpresent = HasProperty(cx, o, pk); if (kpresent) { Object elementk = Get(cx, o, pk); boolean same = strictEqualityComparison(searchElement, elementk); if (same) { return k; } } } return -1; } /** * 15.4.4.16 Array.prototype.every ( callbackfn [ , thisArg ] ) */ @Function(name = "every", arity = 1) public static Object every(ExecutionContext cx, Object thisValue, Object callbackfn, Object thisArg) { ScriptObject o = ToObject(cx, thisValue); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); if (!IsCallable(callbackfn)) { throw throwTypeError(cx, Messages.Key.NotCallable); } Callable callback = (Callable) callbackfn; for (long k = 0; k < len; ++k) { String pk = ToString(k); boolean kpresent = HasProperty(cx, o, pk); if (kpresent) { Object kvalue = Get(cx, o, pk); Object testResult = callback.call(cx, thisArg, kvalue, k, o); if (!ToBoolean(testResult)) { return false; } } } return true; } /** * 15.4.4.17 Array.prototype.some ( callbackfn [ , thisArg ] ) */ @Function(name = "some", arity = 1) public static Object some(ExecutionContext cx, Object thisValue, Object callbackfn, Object thisArg) { ScriptObject o = ToObject(cx, thisValue); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); if (!IsCallable(callbackfn)) { throw throwTypeError(cx, Messages.Key.NotCallable); } Callable callback = (Callable) callbackfn; for (long k = 0; k < len; ++k) { String pk = ToString(k); boolean kpresent = HasProperty(cx, o, pk); if (kpresent) { Object kvalue = Get(cx, o, pk); Object testResult = callback.call(cx, thisArg, kvalue, k, o); if (ToBoolean(testResult)) { return true; } } } return false; } /** * 15.4.4.18 Array.prototype.forEach ( callbackfn [ , thisArg ] ) */ @Function(name = "forEach", arity = 1) public static Object forEach(ExecutionContext cx, Object thisValue, Object callbackfn, Object thisArg) { ScriptObject o = ToObject(cx, thisValue); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); if (!IsCallable(callbackfn)) { throw throwTypeError(cx, Messages.Key.NotCallable); } Callable callback = (Callable) callbackfn; for (long k = 0; k < len; ++k) { String pk = ToString(k); boolean kpresent = HasProperty(cx, o, pk); if (kpresent) { Object kvalue = Get(cx, o, pk); callback.call(cx, thisArg, kvalue, k, o); } } return UNDEFINED; } /** * 15.4.4.19 Array.prototype.map ( callbackfn [ , thisArg ] ) */ @Function(name = "map", arity = 1) public static Object map(ExecutionContext cx, Object thisValue, Object callbackfn, Object thisArg) { ScriptObject o = ToObject(cx, thisValue); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); if (!IsCallable(callbackfn)) { throw throwTypeError(cx, Messages.Key.NotCallable); } Callable callback = (Callable) callbackfn; ScriptObject a = ArrayCreate(cx, len); for (long k = 0; k < len; ++k) { String pk = ToString(k); boolean kpresent = HasProperty(cx, o, pk); if (kpresent) { Object kvalue = Get(cx, o, pk); Object mappedValue = callback.call(cx, thisArg, kvalue, k, o); a.defineOwnProperty(cx, pk, new PropertyDescriptor(mappedValue, true, true, true)); } } return a; } /** * 15.4.4.20 Array.prototype.filter ( callbackfn [ , thisArg ] ) */ @Function(name = "filter", arity = 1) public static Object filter(ExecutionContext cx, Object thisValue, Object callbackfn, Object thisArg) { ScriptObject o = ToObject(cx, thisValue); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); if (!IsCallable(callbackfn)) { throw throwTypeError(cx, Messages.Key.NotCallable); } Callable callback = (Callable) callbackfn; ScriptObject a = ArrayCreate(cx, 0); for (long k = 0, to = 0; k < len; ++k) { String pk = ToString(k); boolean kpresent = HasProperty(cx, o, pk); if (kpresent) { Object kvalue = Get(cx, o, pk); Object selected = callback.call(cx, thisArg, kvalue, k, o); if (ToBoolean(selected)) { a.defineOwnProperty(cx, ToString(to), new PropertyDescriptor(kvalue, true, true, true)); to += 1; } } } return a; } /** * 15.4.4.21 Array.prototype.reduce ( callbackfn [ , initialValue ] ) */ @Function(name = "reduce", arity = 1) public static Object reduce(ExecutionContext cx, Object thisValue, Object callbackfn, @Optional(Optional.Default.NONE) Object initialValue) { ScriptObject o = ToObject(cx, thisValue); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); if (!IsCallable(callbackfn)) { throw throwTypeError(cx, Messages.Key.NotCallable); } Callable callback = (Callable) callbackfn; if (len == 0 && initialValue == null) { throw throwTypeError(cx, Messages.Key.ReduceInitialValue); } long k = 0; Object accumulator = null; if (initialValue != null) { accumulator = initialValue; } else { boolean kpresent = false; for (; !kpresent && k < len; ++k) { String pk = ToString(k); kpresent = HasProperty(cx, o, pk); if (kpresent) { accumulator = Get(cx, o, pk); } } if (!kpresent) { throw throwTypeError(cx, Messages.Key.ReduceInitialValue); } } for (; k < len; ++k) { String pk = ToString(k); boolean kpresent = HasProperty(cx, o, pk); if (kpresent) { Object kvalue = Get(cx, o, pk); accumulator = callback.call(cx, UNDEFINED, accumulator, kvalue, k, o); } } return accumulator; } /** * 15.4.4.22 Array.prototype.reduceRight ( callbackfn [ , initialValue ] ) */ @Function(name = "reduceRight", arity = 1) public static Object reduceRight(ExecutionContext cx, Object thisValue, Object callbackfn, @Optional(Optional.Default.NONE) Object initialValue) { ScriptObject o = ToObject(cx, thisValue); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); if (!IsCallable(callbackfn)) { throw throwTypeError(cx, Messages.Key.NotCallable); } Callable callback = (Callable) callbackfn; if (len == 0 && initialValue == null) { throw throwTypeError(cx, Messages.Key.ReduceInitialValue); } long k = (len - 1); Object accumulator = null; if (initialValue != null) { accumulator = initialValue; } else { boolean kpresent = false; for (; !kpresent && k >= 0; --k) { String pk = ToString(k); kpresent = HasProperty(cx, o, pk); if (kpresent) { accumulator = Get(cx, o, pk); } } if (!kpresent) { throw throwTypeError(cx, Messages.Key.ReduceInitialValue); } } for (; k >= 0; --k) { String pk = ToString(k); boolean kpresent = HasProperty(cx, o, pk); if (kpresent) { Object kvalue = Get(cx, o, pk); accumulator = callback.call(cx, UNDEFINED, accumulator, kvalue, k, o); } } return accumulator; } /** * 15.4.4.23 Array.prototype.items ( ) */ @Function(name = "items", arity = 0) public static Object items(ExecutionContext cx, Object thisValue) { ScriptObject o = ToObject(cx, thisValue); return CreateArrayIterator(cx, o, ArrayIterationKind.KeyValue); } /** * 15.4.4.24 Array.prototype.keys ( ) */ @Function(name = "keys", arity = 0) public static Object keys(ExecutionContext cx, Object thisValue) { ScriptObject o = ToObject(cx, thisValue); return CreateArrayIterator(cx, o, ArrayIterationKind.Key); } /** * 15.4.4.25 Array.prototype.values ( ) */ @Function(name = "values", arity = 0) public static Object values(ExecutionContext cx, Object thisValue) { ScriptObject o = ToObject(cx, thisValue); return CreateArrayIterator(cx, o, ArrayIterationKind.Value); } /** * 15.4.4.x Array.prototype.find ( predicate [ , thisArg ] ) */ @Function(name = "find", arity = 1) public static Object find(ExecutionContext cx, Object thisValue, Object predicate, Object thisArg) { ScriptObject o = ToObject(cx, thisValue); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); // FIXME: spec bug (IsCallable() check should occur before return) (bug 1342) if (!IsCallable(predicate)) { throw throwTypeError(cx, Messages.Key.NotCallable); } Callable pred = (Callable) predicate; if (len == 0) { return UNDEFINED; } for (long k = 0; k < len; ++k) { String pk = ToString(k); boolean kpresent = HasProperty(cx, o, pk); if (kpresent) { Object kvalue = Get(cx, o, pk); Object result = pred.call(cx, thisArg, kvalue, k, o); if (ToBoolean(result)) { return kvalue; } } } return UNDEFINED; } /** * 15.4.4.x Array.prototype.findIndex ( predicate [ , thisArg ] ) */ @Function(name = "findIndex", arity = 1) public static Object findIndex(ExecutionContext cx, Object thisValue, Object predicate, Object thisArg) { ScriptObject o = ToObject(cx, thisValue); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); // FIXME: spec bug (IsCallable() check should occur before return) (bug 1342) if (!IsCallable(predicate)) { throw throwTypeError(cx, Messages.Key.NotCallable); } Callable pred = (Callable) predicate; if (len == 0) { return -1; } for (long k = 0; k < len; ++k) { String pk = ToString(k); boolean kpresent = HasProperty(cx, o, pk); if (kpresent) { Object kvalue = Get(cx, o, pk); Object result = pred.call(cx, thisArg, kvalue, k, o); if (ToBoolean(result)) { return k; } } } return -1; } } }
false
true
public static Object splice(ExecutionContext cx, Object thisValue, Object start, Object deleteCount, Object... items) { ScriptObject o = ToObject(cx, thisValue); ScriptObject a = ArrayCreate(cx, 0); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); double relativeStart = ToInteger(cx, start); long actualStart; if (relativeStart < 0) { actualStart = (long) Math.max(len + relativeStart, 0); } else { actualStart = (long) Math.min(relativeStart, len); } long actualDeleteCount = (long) Math.min(Math.max(ToInteger(cx, deleteCount), 0), len - actualStart); for (long k = 0; k < actualDeleteCount; ++k) { String from = ToString(actualStart + k); boolean fromPresent = HasProperty(cx, o, from); if (fromPresent) { Object fromValue = Get(cx, o, from); a.defineOwnProperty(cx, ToString(k), new PropertyDescriptor(fromValue, true, true, true)); } } Put(cx, a, "length", actualDeleteCount, true); int itemCount = items.length; if (itemCount < actualDeleteCount) { for (long k = actualStart; k < (len - actualDeleteCount); ++k) { String from = ToString(k + actualDeleteCount); String to = ToString(k + itemCount); boolean fromPresent = HasProperty(cx, o, from); if (fromPresent) { Object fromValue = Get(cx, o, from); Put(cx, o, to, fromValue, true); } else { DeletePropertyOrThrow(cx, o, to); } } for (long k = len; k > (len - actualDeleteCount + itemCount); --k) { DeletePropertyOrThrow(cx, o, ToString(k - 1)); } } else if (itemCount > actualDeleteCount) { for (long k = (len - actualDeleteCount); k > actualStart; --k) { String from = ToString(k + actualDeleteCount - 1); String to = ToString(k + itemCount - 1); boolean fromPresent = HasProperty(cx, o, from); if (fromPresent) { Object fromValue = Get(cx, o, from); Put(cx, o, to, fromValue, true); } else { DeletePropertyOrThrow(cx, o, to); } } } long k = actualStart; for (int i = 0; i < itemCount; ++k, ++i) { Object e = items[i]; Put(cx, o, ToString(k), e, true); } Put(cx, o, "length", len - actualDeleteCount + itemCount, true); return a; }
public static Object splice(ExecutionContext cx, Object thisValue, @Optional(Optional.Default.NONE) Object start, @Optional(Optional.Default.NONE) Object deleteCount, Object... items) { ScriptObject o = ToObject(cx, thisValue); ScriptObject a = ArrayCreate(cx, 0); Object lenVal = Get(cx, o, "length"); long len = ToUint32(cx, lenVal); double relativeStart = (start != null ? ToInteger(cx, start) : 0); long actualStart; if (relativeStart < 0) { actualStart = (long) Math.max(len + relativeStart, 0); } else { actualStart = (long) Math.min(relativeStart, len); } // TODO: track spec, https://bugs.ecmascript.org/show_bug.cgi?id=429 long actualDeleteCount; if (start != null && deleteCount == null) { actualDeleteCount = (len - actualStart); } else { double del = (deleteCount != null ? Math.max(ToInteger(cx, deleteCount), 0) : 0); actualDeleteCount = (long) Math.min(del, len - actualStart); } for (long k = 0; k < actualDeleteCount; ++k) { String from = ToString(actualStart + k); boolean fromPresent = HasProperty(cx, o, from); if (fromPresent) { Object fromValue = Get(cx, o, from); a.defineOwnProperty(cx, ToString(k), new PropertyDescriptor(fromValue, true, true, true)); } } Put(cx, a, "length", actualDeleteCount, true); int itemCount = items.length; if (itemCount < actualDeleteCount) { for (long k = actualStart; k < (len - actualDeleteCount); ++k) { String from = ToString(k + actualDeleteCount); String to = ToString(k + itemCount); boolean fromPresent = HasProperty(cx, o, from); if (fromPresent) { Object fromValue = Get(cx, o, from); Put(cx, o, to, fromValue, true); } else { DeletePropertyOrThrow(cx, o, to); } } for (long k = len; k > (len - actualDeleteCount + itemCount); --k) { DeletePropertyOrThrow(cx, o, ToString(k - 1)); } } else if (itemCount > actualDeleteCount) { for (long k = (len - actualDeleteCount); k > actualStart; --k) { String from = ToString(k + actualDeleteCount - 1); String to = ToString(k + itemCount - 1); boolean fromPresent = HasProperty(cx, o, from); if (fromPresent) { Object fromValue = Get(cx, o, from); Put(cx, o, to, fromValue, true); } else { DeletePropertyOrThrow(cx, o, to); } } } long k = actualStart; for (int i = 0; i < itemCount; ++k, ++i) { Object e = items[i]; Put(cx, o, ToString(k), e, true); } Put(cx, o, "length", len - actualDeleteCount + itemCount, true); return a; }
diff --git a/src/actor/ship/weapon/AlternatingWeapon.java b/src/actor/ship/weapon/AlternatingWeapon.java index de55573..1a2a64f 100644 --- a/src/actor/ship/weapon/AlternatingWeapon.java +++ b/src/actor/ship/weapon/AlternatingWeapon.java @@ -1,36 +1,36 @@ package actor.ship.weapon; import actor.ship.projectile.Projectile; import math.Vector3f; public class AlternatingWeapon<T extends Projectile> extends Weapon<T> { private static final long serialVersionUID = 4362231465338858745L; public AlternatingWeapon(Class<? extends T> projectileType, long coolDown,int maxAmmo) { super(projectileType,coolDown/2,maxAmmo); } public final float DEFAULT_OFFSET = 0.5f; public float getOffsetDistance(){ return DEFAULT_OFFSET; } public void shoot(actor.Actor ship) { //calculates time passed in milliseconds if(hasNoAmmo()) return; if((System.currentTimeMillis() - getLastShotTime()) < coolDown) return; actor.ship.projectile.Projectile p = newProjectile(ship); if( currentAmmo % 2 == 0){// Left Shot p.setPosition(p.getPosition().plus(Vector3f.UNIT_X.times(ship.getRotation()).times(-getOffsetDistance()))); } else { // Right Shot p.setPosition(p.getPosition().plus(Vector3f.UNIT_X.times(ship.getRotation()).times(getOffsetDistance()))); } - game.Game.getActors().add(p); + ship.add(p); setLastShotTime(System.currentTimeMillis()); currentAmmo--; } }
true
true
public void shoot(actor.Actor ship) { //calculates time passed in milliseconds if(hasNoAmmo()) return; if((System.currentTimeMillis() - getLastShotTime()) < coolDown) return; actor.ship.projectile.Projectile p = newProjectile(ship); if( currentAmmo % 2 == 0){// Left Shot p.setPosition(p.getPosition().plus(Vector3f.UNIT_X.times(ship.getRotation()).times(-getOffsetDistance()))); } else { // Right Shot p.setPosition(p.getPosition().plus(Vector3f.UNIT_X.times(ship.getRotation()).times(getOffsetDistance()))); } game.Game.getActors().add(p); setLastShotTime(System.currentTimeMillis()); currentAmmo--; }
public void shoot(actor.Actor ship) { //calculates time passed in milliseconds if(hasNoAmmo()) return; if((System.currentTimeMillis() - getLastShotTime()) < coolDown) return; actor.ship.projectile.Projectile p = newProjectile(ship); if( currentAmmo % 2 == 0){// Left Shot p.setPosition(p.getPosition().plus(Vector3f.UNIT_X.times(ship.getRotation()).times(-getOffsetDistance()))); } else { // Right Shot p.setPosition(p.getPosition().plus(Vector3f.UNIT_X.times(ship.getRotation()).times(getOffsetDistance()))); } ship.add(p); setLastShotTime(System.currentTimeMillis()); currentAmmo--; }
diff --git a/new/src/main/java/org/jboss/modules/ModuleClassLoader.java b/new/src/main/java/org/jboss/modules/ModuleClassLoader.java index 46ef7db4..b94730ee 100644 --- a/new/src/main/java/org/jboss/modules/ModuleClassLoader.java +++ b/new/src/main/java/org/jboss/modules/ModuleClassLoader.java @@ -1,324 +1,324 @@ /* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.modules; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.security.SecureClassLoader; import java.util.ArrayDeque; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Queue; import java.util.Set; /** * @author <a href="mailto:[email protected]">John Bailey</a> * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ public final class ModuleClassLoader extends SecureClassLoader { static { try { final Method method = ClassLoader.class.getMethod("registerAsParallelCapable"); method.invoke(null); } catch (Exception e) { // ignore } } private final Module module; private final Set<Module.Flag> flags; private final Map<String, Class<?>> cache = new HashMap<String, Class<?>>(256); ModuleClassLoader(final Module module, final Set<Module.Flag> flags, final AssertionSetting setting) { this.module = module; this.flags = flags; if (setting != AssertionSetting.INHERIT) { setDefaultAssertionStatus(setting == AssertionSetting.ENABLED); } } @Override public Class<?> loadClass(final String name) throws ClassNotFoundException { return loadClass(name, false); } @Override protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException { if (className.startsWith("java.")) { // always delegate to super return super.loadClass(className, resolve); } if (Thread.holdsLock(this) && Thread.currentThread() != LoaderThreadHolder.LOADER_THREAD) { // Only the classloader thread may take this lock; use a condition to relinquish it final LoadRequest req = new LoadRequest(className, resolve, this); final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE; synchronized (LoaderThreadHolder.REQUEST_QUEUE) { queue.add(req); queue.notify(); } boolean intr = false; try { while (!req.done) try { wait(); } catch (InterruptedException e) { intr = true; } } finally { if (intr) Thread.currentThread().interrupt(); } return req.result; } else { // no deadlock risk! Either the lock isn't held, or we're inside the class loader thread. if (className == null) { throw new IllegalArgumentException("name is null"); } // Check if we have already loaded it.. Class<?> loadedClass = findLoadedClass(className); if (loadedClass != null) { return loadedClass; } final Map<String, Class<?>> cache = this.cache; final boolean missing; synchronized (this) { missing = cache.containsKey(className); loadedClass = cache.get(className); } if (loadedClass != null) { return loadedClass; } if (missing) { throw new ClassNotFoundException(className); } if (flags.contains(Module.Flag.CHILD_FIRST)) { loadedClass = loadClassLocal(className); if (loadedClass == null) { loadedClass = module.getImportedClass(className); } if (loadedClass == null) try { loadedClass = findSystemClass(className); } catch (ClassNotFoundException e) { } } else { loadedClass = module.getImportedClass(className); if (loadedClass == null) try { loadedClass = findSystemClass(className); } catch (ClassNotFoundException e) { } if (loadedClass == null) { loadedClass = loadClassLocal(className); } } if (loadedClass == null) { if (! flags.contains(Module.Flag.NO_BLACKLIST)) { synchronized (this) { - cache.put(className, loadedClass); + cache.put(className, null); } } throw new ClassNotFoundException(className); } synchronized (this) { cache.put(className, loadedClass); } if (loadedClass != null && resolve) resolveClass(loadedClass); return loadedClass; } } private Class<?> loadClassLocal(String name) throws ClassNotFoundException { // Check to see if we can load it ClassSpec classSpec = null; try { classSpec = module.getLocalClassSpec(name); } catch (IOException e) { throw new ClassNotFoundException(name, e); } if (classSpec == null) return null; return defineClass(name, classSpec); } private Class<?> defineClass(final String name, final ClassSpec classSpec) { // Ensure that the package is loaded final int lastIdx = name.lastIndexOf('.'); if (lastIdx != -1) { // there's a package name; get the Package for it final String packageName = name.substring(0, lastIdx); final Package pkg = getPackage(packageName); if (pkg != null) { // Package is defined already if (pkg.isSealed() && ! pkg.isSealed(classSpec.getCodeSource().getLocation())) { // use the same message as the JDK throw new SecurityException("sealing violation: package " + packageName + " is sealed"); } } else { final PackageSpec spec; try { spec = getModule().getLocalPackageSpec(name); definePackage(name, spec); } catch (IOException e) { definePackage(name, null); } } } final Class<?> newClass = defineClass(name, classSpec.getBytes(), 0, classSpec.getBytes().length, classSpec.getCodeSource()); final AssertionSetting setting = classSpec.getAssertionSetting(); if (setting != AssertionSetting.INHERIT) { setClassAssertionStatus(name, setting == AssertionSetting.ENABLED); } return newClass; } private Package definePackage(final String name, final PackageSpec spec) { if (spec == null) { return definePackage(name, null, null, null, null, null, null, null); } else { final Package pkg = definePackage(name, spec.getSpecTitle(), spec.getSpecVersion(), spec.getSpecVendor(), spec.getImplTitle(), spec.getImplVersion(), spec.getImplVendor(), spec.getSealBase()); final AssertionSetting setting = spec.getAssertionSetting(); if (setting != AssertionSetting.INHERIT) { setPackageAssertionStatus(name, setting == AssertionSetting.ENABLED); } return pkg; } } @Override protected String findLibrary(final String libname) { return module.getLocalLibrary(libname); } @Override public URL getResource(String name) { return module.getExportedResource(name).getURL(); } @Override public Enumeration<URL> getResources(String name) throws IOException { final Iterable<Resource> resources = module.getExportedResources(name); final Iterator<Resource> iterator = resources.iterator(); return new Enumeration<URL>() { @Override public boolean hasMoreElements() { return iterator.hasNext(); } @Override public URL nextElement() { return iterator.next().getURL(); } }; } @Override public InputStream getResourceAsStream(final String name) { try { return module.getExportedResource(name).openStream(); } catch (IOException e) { return null; } } /** * Get the module for this class loader. * * @return the module */ public Module getModule() { return module; } private static final class LoaderThreadHolder { private static final Thread LOADER_THREAD; private static final Queue<LoadRequest> REQUEST_QUEUE = new ArrayDeque<LoadRequest>(); static { Thread thr = new LoaderThread(); thr.setName("Module ClassLoader Thread"); // This thread will always run as long as the VM is alive. thr.setDaemon(true); thr.start(); LOADER_THREAD = thr; } private LoaderThreadHolder() { } } static class LoadRequest { private final String className; private final ModuleClassLoader requester; private Class<?> result; private boolean resolve; private boolean done; public LoadRequest(final String className, final boolean resolve, final ModuleClassLoader requester) { this.className = className; this.resolve = resolve; this.requester = requester; } } static class LoaderThread extends Thread { @Override public void run() { final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE; for (; ;) { try { LoadRequest request; synchronized (queue) { while ((request = queue.poll()) == null) { try { queue.wait(); } catch (InterruptedException e) { } } } final ModuleClassLoader loader = request.requester; Class<?> result = null; synchronized (loader) { try { result = loader.loadClass(request.className, request.resolve); } finally { // no matter what, the requester MUST be notified request.result = result; request.done = true; loader.notifyAll(); } } } catch (Throwable t) { // ignore } } } } }
true
true
protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException { if (className.startsWith("java.")) { // always delegate to super return super.loadClass(className, resolve); } if (Thread.holdsLock(this) && Thread.currentThread() != LoaderThreadHolder.LOADER_THREAD) { // Only the classloader thread may take this lock; use a condition to relinquish it final LoadRequest req = new LoadRequest(className, resolve, this); final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE; synchronized (LoaderThreadHolder.REQUEST_QUEUE) { queue.add(req); queue.notify(); } boolean intr = false; try { while (!req.done) try { wait(); } catch (InterruptedException e) { intr = true; } } finally { if (intr) Thread.currentThread().interrupt(); } return req.result; } else { // no deadlock risk! Either the lock isn't held, or we're inside the class loader thread. if (className == null) { throw new IllegalArgumentException("name is null"); } // Check if we have already loaded it.. Class<?> loadedClass = findLoadedClass(className); if (loadedClass != null) { return loadedClass; } final Map<String, Class<?>> cache = this.cache; final boolean missing; synchronized (this) { missing = cache.containsKey(className); loadedClass = cache.get(className); } if (loadedClass != null) { return loadedClass; } if (missing) { throw new ClassNotFoundException(className); } if (flags.contains(Module.Flag.CHILD_FIRST)) { loadedClass = loadClassLocal(className); if (loadedClass == null) { loadedClass = module.getImportedClass(className); } if (loadedClass == null) try { loadedClass = findSystemClass(className); } catch (ClassNotFoundException e) { } } else { loadedClass = module.getImportedClass(className); if (loadedClass == null) try { loadedClass = findSystemClass(className); } catch (ClassNotFoundException e) { } if (loadedClass == null) { loadedClass = loadClassLocal(className); } } if (loadedClass == null) { if (! flags.contains(Module.Flag.NO_BLACKLIST)) { synchronized (this) { cache.put(className, loadedClass); } } throw new ClassNotFoundException(className); } synchronized (this) { cache.put(className, loadedClass); } if (loadedClass != null && resolve) resolveClass(loadedClass); return loadedClass; } }
protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException { if (className.startsWith("java.")) { // always delegate to super return super.loadClass(className, resolve); } if (Thread.holdsLock(this) && Thread.currentThread() != LoaderThreadHolder.LOADER_THREAD) { // Only the classloader thread may take this lock; use a condition to relinquish it final LoadRequest req = new LoadRequest(className, resolve, this); final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE; synchronized (LoaderThreadHolder.REQUEST_QUEUE) { queue.add(req); queue.notify(); } boolean intr = false; try { while (!req.done) try { wait(); } catch (InterruptedException e) { intr = true; } } finally { if (intr) Thread.currentThread().interrupt(); } return req.result; } else { // no deadlock risk! Either the lock isn't held, or we're inside the class loader thread. if (className == null) { throw new IllegalArgumentException("name is null"); } // Check if we have already loaded it.. Class<?> loadedClass = findLoadedClass(className); if (loadedClass != null) { return loadedClass; } final Map<String, Class<?>> cache = this.cache; final boolean missing; synchronized (this) { missing = cache.containsKey(className); loadedClass = cache.get(className); } if (loadedClass != null) { return loadedClass; } if (missing) { throw new ClassNotFoundException(className); } if (flags.contains(Module.Flag.CHILD_FIRST)) { loadedClass = loadClassLocal(className); if (loadedClass == null) { loadedClass = module.getImportedClass(className); } if (loadedClass == null) try { loadedClass = findSystemClass(className); } catch (ClassNotFoundException e) { } } else { loadedClass = module.getImportedClass(className); if (loadedClass == null) try { loadedClass = findSystemClass(className); } catch (ClassNotFoundException e) { } if (loadedClass == null) { loadedClass = loadClassLocal(className); } } if (loadedClass == null) { if (! flags.contains(Module.Flag.NO_BLACKLIST)) { synchronized (this) { cache.put(className, null); } } throw new ClassNotFoundException(className); } synchronized (this) { cache.put(className, loadedClass); } if (loadedClass != null && resolve) resolveClass(loadedClass); return loadedClass; } }
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/api/LocalizedMessage.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/api/LocalizedMessage.java index 2314bbb0f..e6adad0b9 100644 --- a/src/checkstyle/com/puppycrawl/tools/checkstyle/api/LocalizedMessage.java +++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/api/LocalizedMessage.java @@ -1,214 +1,224 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2002 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import java.text.MessageFormat; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * Represents a message that can be localised. The translations come from * message.properties files. The underlying implementation uses * java.text.MessageFormat. * * @author <a href="mailto:[email protected]">Oliver Burn</a> * @author lkuehne * @version 1.0 */ public final class LocalizedMessage implements Comparable { /** the locale to localise messages to **/ private static Locale sLocale = Locale.getDefault(); /** * A cache that maps bundle names to RessourceBundles. * Avoids repetitive calls to ResourceBundle.getBundle(). * TODO: The cache should be cleared at some point. */ private static Map sBundleCache = new HashMap(); /** the line number **/ private final int mLineNo; /** the column number **/ private final int mColNo; /** key for the message format **/ private final String mKey; /** arguments for MessageFormat **/ private final Object[] mArgs; /** name of the resource bundle to get messages from **/ private final String mBundle; /** @see Object#equals */ - public boolean equals(Object o) + public boolean equals(Object aObject) { - if (this == o) return true; - if (!(o instanceof LocalizedMessage)) return false; + if (this == aObject) { + return true; + } + if (!(aObject instanceof LocalizedMessage)) { + return false; + } - final LocalizedMessage localizedMessage = (LocalizedMessage) o; + final LocalizedMessage localizedMessage = (LocalizedMessage) aObject; - if (mColNo != localizedMessage.mColNo) return false; - if (mLineNo != localizedMessage.mLineNo) return false; - if (!mKey.equals(localizedMessage.mKey)) return false; + if (mColNo != localizedMessage.mColNo) { + return false; + } + if (mLineNo != localizedMessage.mLineNo) { + return false; + } + if (!mKey.equals(localizedMessage.mKey)) { + return false; + } // ignoring mArgs and mBundle for perf reasons. // we currently never load the same error from different bundles or // fire the same error for the same location with different arguments. return true; } /** * @see Object#hashCode */ public int hashCode() { int result; result = mLineNo; result = 29 * result + mColNo; result = 29 * result + mKey.hashCode(); return result; } /** * Creates a new <code>LocalizedMessage</code> instance. * * @param aLineNo line number associated with the message * @param aColNo column number associated with the message * @param aBundle resource bundle name * @param aKey the key to locate the translation * @param aArgs arguments for the translation */ public LocalizedMessage(int aLineNo, int aColNo, String aBundle, String aKey, Object[] aArgs) { mLineNo = aLineNo; mColNo = aColNo; mKey = aKey; mArgs = aArgs; mBundle = aBundle; } /** * Creates a new <code>LocalizedMessage</code> instance. The column number * defaults to 0. * * @param aLineNo line number associated with the message * @param aBundle name of a resource bundle that contains error messages * @param aKey the key to locate the translation * @param aArgs arguments for the translation */ public LocalizedMessage( int aLineNo, String aBundle, String aKey, Object[] aArgs) { this(aLineNo, 0, aBundle, aKey, aArgs); } /** @return the translated message **/ public String getMessage() { try { // Important to use the default class loader, and not the one in // the GlobalProperties object. This is because the class loader in // the GlobalProperties is specified by the user for resolving // custom classes. final ResourceBundle bundle = getBundle(mBundle); final String pattern = bundle.getString(mKey); return MessageFormat.format(pattern, mArgs); } catch (MissingResourceException ex) { // If the Check author didn't provide i18n resource bundles // and logs error messages directly, this will return // the author's original message return MessageFormat.format(mKey, mArgs); } } /** * Find a ResourceBundle for a given bundle name. * @param aBundleName the bundle name * @return a ResourceBundle */ private static ResourceBundle getBundle(String aBundleName) { ResourceBundle bundle = (ResourceBundle) sBundleCache.get(aBundleName); if (bundle == null) { bundle = ResourceBundle.getBundle(aBundleName, sLocale); sBundleCache.put(aBundleName, bundle); } return bundle; } /** @return the line number **/ public int getLineNo() { return mLineNo; } /** @return the column number **/ public int getColumnNo() { return mColNo; } /** * Returns the message key to locate the translation, can also be used * in IDE plugins to map error messages to corrective actions. * * @return the message key */ public String getKey() { return mKey; } /** @param aLocale the locale to use for localization **/ public static void setLocale(Locale aLocale) { sLocale = aLocale; } //////////////////////////////////////////////////////////////////////////// // Interface Comparable methods //////////////////////////////////////////////////////////////////////////// /** @see java.lang.Comparable **/ public int compareTo(Object aOther) { final LocalizedMessage lt = (LocalizedMessage) aOther; if (getLineNo() == lt.getLineNo()) { if (getColumnNo() == lt.getColumnNo()) { return mKey.compareTo(lt.mKey); } return (getColumnNo() < lt.getColumnNo()) ? -1 : 1; } return (getLineNo() < lt.getLineNo()) ? -1 : 1; } }
false
true
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof LocalizedMessage)) return false; final LocalizedMessage localizedMessage = (LocalizedMessage) o; if (mColNo != localizedMessage.mColNo) return false; if (mLineNo != localizedMessage.mLineNo) return false; if (!mKey.equals(localizedMessage.mKey)) return false; // ignoring mArgs and mBundle for perf reasons. // we currently never load the same error from different bundles or // fire the same error for the same location with different arguments. return true; }
public boolean equals(Object aObject) { if (this == aObject) { return true; } if (!(aObject instanceof LocalizedMessage)) { return false; } final LocalizedMessage localizedMessage = (LocalizedMessage) aObject; if (mColNo != localizedMessage.mColNo) { return false; } if (mLineNo != localizedMessage.mLineNo) { return false; } if (!mKey.equals(localizedMessage.mKey)) { return false; } // ignoring mArgs and mBundle for perf reasons. // we currently never load the same error from different bundles or // fire the same error for the same location with different arguments. return true; }
diff --git a/user/src/com/google/gwt/i18n/rebind/AbstractLocalizableImplCreator.java b/user/src/com/google/gwt/i18n/rebind/AbstractLocalizableImplCreator.java index 71104daa3..b4c4d4dc1 100644 --- a/user/src/com/google/gwt/i18n/rebind/AbstractLocalizableImplCreator.java +++ b/user/src/com/google/gwt/i18n/rebind/AbstractLocalizableImplCreator.java @@ -1,329 +1,332 @@ /* * Copyright 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.i18n.rebind; import com.google.gwt.core.ext.GeneratorContext; import com.google.gwt.core.ext.TreeLogger; import com.google.gwt.core.ext.UnableToCompleteException; import com.google.gwt.core.ext.typeinfo.JClassType; import com.google.gwt.core.ext.typeinfo.JMethod; import com.google.gwt.core.ext.typeinfo.NotFoundException; import com.google.gwt.core.ext.typeinfo.TypeOracle; import com.google.gwt.i18n.client.LocalizableResource.Generate; import com.google.gwt.i18n.client.LocalizableResource.Key; import com.google.gwt.i18n.rebind.AnnotationsResource.AnnotationsError; import com.google.gwt.i18n.rebind.format.MessageCatalogFormat; import com.google.gwt.i18n.rebind.keygen.KeyGenerator; import com.google.gwt.user.rebind.AbstractGeneratorClassCreator; import com.google.gwt.user.rebind.AbstractMethodCreator; import com.google.gwt.user.rebind.ClassSourceFileComposerFactory; import com.google.gwt.user.rebind.SourceWriter; import java.io.BufferedWriter; import java.io.File; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.MissingResourceException; /** * Represents generic functionality needed for <code>Constants</code> and * <code>Messages</code> classes. */ abstract class AbstractLocalizableImplCreator extends AbstractGeneratorClassCreator { static String generateConstantOrMessageClass(TreeLogger logger, TreeLogger deprecatedLogger, GeneratorContext context, String locale, JClassType targetClass) throws UnableToCompleteException { TypeOracle oracle = context.getTypeOracle(); JClassType constantsClass; JClassType messagesClass; JClassType constantsWithLookupClass; boolean seenError = false; try { constantsClass = oracle.getType(LocalizableGenerator.CONSTANTS_NAME); constantsWithLookupClass = oracle.getType(LocalizableGenerator.CONSTANTS_WITH_LOOKUP_NAME); messagesClass = oracle.getType(LocalizableGenerator.MESSAGES_NAME); } catch (NotFoundException e) { // Should never happen in practice. throw error(logger, e); } String name = targetClass.getName(); String packageName = targetClass.getPackage().getName(); // Make sure the interface being rebound extends either Constants or // Messages. boolean assignableToConstants = constantsClass.isAssignableFrom(targetClass); boolean assignableToMessages = messagesClass.isAssignableFrom(targetClass); if (!assignableToConstants && !assignableToMessages) { // Let the implementation generator handle this interface. return null; } // Make sure that they don't try to extend both Messages and Constants. if (assignableToConstants && assignableToMessages) { throw error(logger, name + " cannot extend both Constants and Messages"); } // Make sure that the type being rebound is in fact an interface. if (targetClass.isInterface() == null) { throw error(logger, name + " must be an interface"); } AbstractResource resource = null; try { resource = ResourceFactory.getBundle(logger, targetClass, locale, assignableToConstants); } catch (MissingResourceException e) { throw error( logger, "Localization failed; there must be at least one properties file accessible through" + " the classpath in package '" + packageName + "' whose base name is '" + ResourceFactory.getResourceName(targetClass) + "'"); } catch (IllegalArgumentException e) { // A bad key can generate an illegal argument exception. throw error(logger, e.getMessage()); } // generated implementations for interface X will be named X_, X_en, // X_en_CA, etc. String localeSuffix = String.valueOf(ResourceFactory.LOCALE_SEPARATOR); if (!ResourceFactory.DEFAULT_TOKEN.equals(locale)) { localeSuffix += locale; } // Use _ rather than "." in class name, cannot use $ String resourceName = targetClass.getName().replace('.', '_'); String className = resourceName + localeSuffix; PrintWriter pw = context.tryCreate(logger, packageName, className); if (pw != null) { ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory( packageName, className); factory.addImplementedInterface(targetClass.getQualifiedSourceName()); SourceWriter writer = factory.createSourceWriter(context, pw); // Now that we have all the information set up, process the class if (constantsWithLookupClass.isAssignableFrom(targetClass)) { ConstantsWithLookupImplCreator c = new ConstantsWithLookupImplCreator( logger, deprecatedLogger, writer, targetClass, resource, context.getTypeOracle()); c.emitClass(logger, locale); } else if (constantsClass.isAssignableFrom(targetClass)) { ConstantsImplCreator c = new ConstantsImplCreator(logger, deprecatedLogger, writer, targetClass, resource, context.getTypeOracle()); c.emitClass(logger, locale); } else { MessagesImplCreator messages = new MessagesImplCreator(logger, deprecatedLogger, writer, targetClass, resource, context.getTypeOracle()); messages.emitClass(logger, locale); } context.commit(logger, pw); } // Generate a translatable output file if requested. Generate generate = targetClass.getAnnotation(Generate.class); if (generate != null) { String path = generate.fileName(); if (Generate.DEFAULT.equals(path)) { path = targetClass.getPackage().getName() + "." + targetClass.getName().replace('.', '_'); } else if (path.endsWith(File.pathSeparator)) { path = path + targetClass.getName().replace('.', '_'); } String[] genLocales = generate.locales(); boolean found = false; if (genLocales.length != 0) { // verify the current locale is in the list for (String genLocale : genLocales) { if (genLocale.equals(locale)) { found = true; break; } } } else { // Since they want all locales, this is guaranteed to be one of them. found = true; } if (found) { for (String genClassName : generate.format()) { MessageCatalogFormat msgWriter = null; try { Class<? extends MessageCatalogFormat> msgFormatClass = Class.forName( genClassName).asSubclass(MessageCatalogFormat.class); msgWriter = msgFormatClass.newInstance(); } catch (InstantiationException e) { - logger.log(TreeLogger.WARN, "Error instantiating @Generate class " + genClassName, e); + logger.log(TreeLogger.ERROR, "Error instantiating @Generate class " + genClassName, e); + seenError = true; continue; } catch (IllegalAccessException e) { - logger.log(TreeLogger.WARN, "@Generate class " + genClassName + " illegal access", e); + logger.log(TreeLogger.ERROR, "@Generate class " + genClassName + " illegal access", e); + seenError = true; continue; } catch (ClassNotFoundException e) { - logger.log(TreeLogger.WARN, "@Generate class " + genClassName + " not found"); + logger.log(TreeLogger.ERROR, "@Generate class " + genClassName + " not found"); + seenError = true; continue; } // Make generator-specific changes to a temporary copy of the path. String genPath = path; if (genLocales.length != 1) { // If the user explicitly specified only one locale, do not add the locale. genPath += '_' + locale; } genPath += msgWriter.getExtension(); OutputStream outStr = context.tryCreateResource(logger, genPath); if (outStr != null) { TreeLogger branch = logger.branch(TreeLogger.INFO, "Generating " + genPath + " from " + className + " for locale " + locale, null); PrintWriter out = null; try { out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(outStr, "UTF-8")), false); } catch (UnsupportedEncodingException e) { throw error(logger, e.getMessage()); } try { msgWriter.write(branch, resource, out, targetClass); out.flush(); context.commitResource(logger, outStr).setPrivate(true); } catch (UnableToCompleteException e) { // msgWriter should have already logged an error message. // Keep going for now so we can find other errors. seenError = true; } } } } } if (seenError) { // If one of our generators had a fatal error, don't complete normally. throw new UnableToCompleteException(); } return packageName + "." + className; } /** * Generator to use to create keys for messages. */ private KeyGenerator keyGenerator; /** * The Dictionary/value bindings used to determine message contents. */ private AbstractResource messageBindings; /** * Logger to use for deprecated warnings. */ private TreeLogger deprecatedLogger; /** * True if the class being generated uses Constants-style annotations/quoting. */ private boolean isConstants; /** * Constructor for <code>AbstractLocalizableImplCreator</code>. * * @param deprecatedLogger logger to use for deprecated warnings. * @param writer writer * @param targetClass current target * @param messageBindings backing resource */ public AbstractLocalizableImplCreator(TreeLogger logger, TreeLogger deprecatedLogger, SourceWriter writer, JClassType targetClass, AbstractResource messageBindings, boolean isConstants) { super(writer, targetClass); this.deprecatedLogger = deprecatedLogger; this.messageBindings = messageBindings; this.isConstants = isConstants; try { keyGenerator = AnnotationsResource.getKeyGenerator(targetClass); } catch (AnnotationsError e) { logger.log(TreeLogger.WARN, "Error getting key generator for " + targetClass.getQualifiedSourceName(), e); } } /** * Gets the resource associated with this class. * * @return the resource */ public AbstractResource getResourceBundle() { return messageBindings; } @Override protected String branchMessage() { return "Processing " + this.getTarget(); } /** * Find the creator associated with the given method, and delegate the * creation of the method body to it. * * @param logger TreeLogger instance for logging * @param method method to be generated * @param locale locale to generate * @throws UnableToCompleteException */ protected void delegateToCreator(TreeLogger logger, JMethod method, String locale) throws UnableToCompleteException { AbstractMethodCreator methodCreator = getMethodCreator(logger, method); String key = getKey(logger, method); if (key == null) { logger.log(TreeLogger.ERROR, "Unable to get or compute key for method " + method.getName(), null); throw new UnableToCompleteException(); } methodCreator.createMethodFor(logger, method, key, messageBindings, locale); } /** * Returns a resource key given a method name. * * @param logger TreeLogger instance for logging * @param method method to get key for * @return the key to use for resource lookups or null if unable to get * or compute the key */ protected String getKey(TreeLogger logger, JMethod method) { Key key = method.getAnnotation(Key.class); if (key != null) { return key.value(); } String[][] id = method.getMetaData(LocalizableGenerator.GWT_KEY); if (id.length > 0) { warnOnMetadata(method); if (id[0].length == 0) { logger.log(TreeLogger.WARN, method + " had a mislabeled gwt.key, using default key", null); } else { String tag = id[0][0]; return tag; } } return AnnotationsResource.getKey(logger, keyGenerator, method, isConstants); } /** * Issue a warning about deprecated metadata. * * @param method method to warn about */ void warnOnMetadata(JMethod method) { deprecatedLogger.log(TreeLogger.WARN, "Deprecated metadata found on " + method.getEnclosingType().getSimpleSourceName() + "." + method.getName() + ";svn use annotations instead", null); } }
false
true
static String generateConstantOrMessageClass(TreeLogger logger, TreeLogger deprecatedLogger, GeneratorContext context, String locale, JClassType targetClass) throws UnableToCompleteException { TypeOracle oracle = context.getTypeOracle(); JClassType constantsClass; JClassType messagesClass; JClassType constantsWithLookupClass; boolean seenError = false; try { constantsClass = oracle.getType(LocalizableGenerator.CONSTANTS_NAME); constantsWithLookupClass = oracle.getType(LocalizableGenerator.CONSTANTS_WITH_LOOKUP_NAME); messagesClass = oracle.getType(LocalizableGenerator.MESSAGES_NAME); } catch (NotFoundException e) { // Should never happen in practice. throw error(logger, e); } String name = targetClass.getName(); String packageName = targetClass.getPackage().getName(); // Make sure the interface being rebound extends either Constants or // Messages. boolean assignableToConstants = constantsClass.isAssignableFrom(targetClass); boolean assignableToMessages = messagesClass.isAssignableFrom(targetClass); if (!assignableToConstants && !assignableToMessages) { // Let the implementation generator handle this interface. return null; } // Make sure that they don't try to extend both Messages and Constants. if (assignableToConstants && assignableToMessages) { throw error(logger, name + " cannot extend both Constants and Messages"); } // Make sure that the type being rebound is in fact an interface. if (targetClass.isInterface() == null) { throw error(logger, name + " must be an interface"); } AbstractResource resource = null; try { resource = ResourceFactory.getBundle(logger, targetClass, locale, assignableToConstants); } catch (MissingResourceException e) { throw error( logger, "Localization failed; there must be at least one properties file accessible through" + " the classpath in package '" + packageName + "' whose base name is '" + ResourceFactory.getResourceName(targetClass) + "'"); } catch (IllegalArgumentException e) { // A bad key can generate an illegal argument exception. throw error(logger, e.getMessage()); } // generated implementations for interface X will be named X_, X_en, // X_en_CA, etc. String localeSuffix = String.valueOf(ResourceFactory.LOCALE_SEPARATOR); if (!ResourceFactory.DEFAULT_TOKEN.equals(locale)) { localeSuffix += locale; } // Use _ rather than "." in class name, cannot use $ String resourceName = targetClass.getName().replace('.', '_'); String className = resourceName + localeSuffix; PrintWriter pw = context.tryCreate(logger, packageName, className); if (pw != null) { ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory( packageName, className); factory.addImplementedInterface(targetClass.getQualifiedSourceName()); SourceWriter writer = factory.createSourceWriter(context, pw); // Now that we have all the information set up, process the class if (constantsWithLookupClass.isAssignableFrom(targetClass)) { ConstantsWithLookupImplCreator c = new ConstantsWithLookupImplCreator( logger, deprecatedLogger, writer, targetClass, resource, context.getTypeOracle()); c.emitClass(logger, locale); } else if (constantsClass.isAssignableFrom(targetClass)) { ConstantsImplCreator c = new ConstantsImplCreator(logger, deprecatedLogger, writer, targetClass, resource, context.getTypeOracle()); c.emitClass(logger, locale); } else { MessagesImplCreator messages = new MessagesImplCreator(logger, deprecatedLogger, writer, targetClass, resource, context.getTypeOracle()); messages.emitClass(logger, locale); } context.commit(logger, pw); } // Generate a translatable output file if requested. Generate generate = targetClass.getAnnotation(Generate.class); if (generate != null) { String path = generate.fileName(); if (Generate.DEFAULT.equals(path)) { path = targetClass.getPackage().getName() + "." + targetClass.getName().replace('.', '_'); } else if (path.endsWith(File.pathSeparator)) { path = path + targetClass.getName().replace('.', '_'); } String[] genLocales = generate.locales(); boolean found = false; if (genLocales.length != 0) { // verify the current locale is in the list for (String genLocale : genLocales) { if (genLocale.equals(locale)) { found = true; break; } } } else { // Since they want all locales, this is guaranteed to be one of them. found = true; } if (found) { for (String genClassName : generate.format()) { MessageCatalogFormat msgWriter = null; try { Class<? extends MessageCatalogFormat> msgFormatClass = Class.forName( genClassName).asSubclass(MessageCatalogFormat.class); msgWriter = msgFormatClass.newInstance(); } catch (InstantiationException e) { logger.log(TreeLogger.WARN, "Error instantiating @Generate class " + genClassName, e); continue; } catch (IllegalAccessException e) { logger.log(TreeLogger.WARN, "@Generate class " + genClassName + " illegal access", e); continue; } catch (ClassNotFoundException e) { logger.log(TreeLogger.WARN, "@Generate class " + genClassName + " not found"); continue; } // Make generator-specific changes to a temporary copy of the path. String genPath = path; if (genLocales.length != 1) { // If the user explicitly specified only one locale, do not add the locale. genPath += '_' + locale; } genPath += msgWriter.getExtension(); OutputStream outStr = context.tryCreateResource(logger, genPath); if (outStr != null) { TreeLogger branch = logger.branch(TreeLogger.INFO, "Generating " + genPath + " from " + className + " for locale " + locale, null); PrintWriter out = null; try { out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(outStr, "UTF-8")), false); } catch (UnsupportedEncodingException e) { throw error(logger, e.getMessage()); } try { msgWriter.write(branch, resource, out, targetClass); out.flush(); context.commitResource(logger, outStr).setPrivate(true); } catch (UnableToCompleteException e) { // msgWriter should have already logged an error message. // Keep going for now so we can find other errors. seenError = true; } } } } } if (seenError) { // If one of our generators had a fatal error, don't complete normally. throw new UnableToCompleteException(); } return packageName + "." + className; }
static String generateConstantOrMessageClass(TreeLogger logger, TreeLogger deprecatedLogger, GeneratorContext context, String locale, JClassType targetClass) throws UnableToCompleteException { TypeOracle oracle = context.getTypeOracle(); JClassType constantsClass; JClassType messagesClass; JClassType constantsWithLookupClass; boolean seenError = false; try { constantsClass = oracle.getType(LocalizableGenerator.CONSTANTS_NAME); constantsWithLookupClass = oracle.getType(LocalizableGenerator.CONSTANTS_WITH_LOOKUP_NAME); messagesClass = oracle.getType(LocalizableGenerator.MESSAGES_NAME); } catch (NotFoundException e) { // Should never happen in practice. throw error(logger, e); } String name = targetClass.getName(); String packageName = targetClass.getPackage().getName(); // Make sure the interface being rebound extends either Constants or // Messages. boolean assignableToConstants = constantsClass.isAssignableFrom(targetClass); boolean assignableToMessages = messagesClass.isAssignableFrom(targetClass); if (!assignableToConstants && !assignableToMessages) { // Let the implementation generator handle this interface. return null; } // Make sure that they don't try to extend both Messages and Constants. if (assignableToConstants && assignableToMessages) { throw error(logger, name + " cannot extend both Constants and Messages"); } // Make sure that the type being rebound is in fact an interface. if (targetClass.isInterface() == null) { throw error(logger, name + " must be an interface"); } AbstractResource resource = null; try { resource = ResourceFactory.getBundle(logger, targetClass, locale, assignableToConstants); } catch (MissingResourceException e) { throw error( logger, "Localization failed; there must be at least one properties file accessible through" + " the classpath in package '" + packageName + "' whose base name is '" + ResourceFactory.getResourceName(targetClass) + "'"); } catch (IllegalArgumentException e) { // A bad key can generate an illegal argument exception. throw error(logger, e.getMessage()); } // generated implementations for interface X will be named X_, X_en, // X_en_CA, etc. String localeSuffix = String.valueOf(ResourceFactory.LOCALE_SEPARATOR); if (!ResourceFactory.DEFAULT_TOKEN.equals(locale)) { localeSuffix += locale; } // Use _ rather than "." in class name, cannot use $ String resourceName = targetClass.getName().replace('.', '_'); String className = resourceName + localeSuffix; PrintWriter pw = context.tryCreate(logger, packageName, className); if (pw != null) { ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory( packageName, className); factory.addImplementedInterface(targetClass.getQualifiedSourceName()); SourceWriter writer = factory.createSourceWriter(context, pw); // Now that we have all the information set up, process the class if (constantsWithLookupClass.isAssignableFrom(targetClass)) { ConstantsWithLookupImplCreator c = new ConstantsWithLookupImplCreator( logger, deprecatedLogger, writer, targetClass, resource, context.getTypeOracle()); c.emitClass(logger, locale); } else if (constantsClass.isAssignableFrom(targetClass)) { ConstantsImplCreator c = new ConstantsImplCreator(logger, deprecatedLogger, writer, targetClass, resource, context.getTypeOracle()); c.emitClass(logger, locale); } else { MessagesImplCreator messages = new MessagesImplCreator(logger, deprecatedLogger, writer, targetClass, resource, context.getTypeOracle()); messages.emitClass(logger, locale); } context.commit(logger, pw); } // Generate a translatable output file if requested. Generate generate = targetClass.getAnnotation(Generate.class); if (generate != null) { String path = generate.fileName(); if (Generate.DEFAULT.equals(path)) { path = targetClass.getPackage().getName() + "." + targetClass.getName().replace('.', '_'); } else if (path.endsWith(File.pathSeparator)) { path = path + targetClass.getName().replace('.', '_'); } String[] genLocales = generate.locales(); boolean found = false; if (genLocales.length != 0) { // verify the current locale is in the list for (String genLocale : genLocales) { if (genLocale.equals(locale)) { found = true; break; } } } else { // Since they want all locales, this is guaranteed to be one of them. found = true; } if (found) { for (String genClassName : generate.format()) { MessageCatalogFormat msgWriter = null; try { Class<? extends MessageCatalogFormat> msgFormatClass = Class.forName( genClassName).asSubclass(MessageCatalogFormat.class); msgWriter = msgFormatClass.newInstance(); } catch (InstantiationException e) { logger.log(TreeLogger.ERROR, "Error instantiating @Generate class " + genClassName, e); seenError = true; continue; } catch (IllegalAccessException e) { logger.log(TreeLogger.ERROR, "@Generate class " + genClassName + " illegal access", e); seenError = true; continue; } catch (ClassNotFoundException e) { logger.log(TreeLogger.ERROR, "@Generate class " + genClassName + " not found"); seenError = true; continue; } // Make generator-specific changes to a temporary copy of the path. String genPath = path; if (genLocales.length != 1) { // If the user explicitly specified only one locale, do not add the locale. genPath += '_' + locale; } genPath += msgWriter.getExtension(); OutputStream outStr = context.tryCreateResource(logger, genPath); if (outStr != null) { TreeLogger branch = logger.branch(TreeLogger.INFO, "Generating " + genPath + " from " + className + " for locale " + locale, null); PrintWriter out = null; try { out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(outStr, "UTF-8")), false); } catch (UnsupportedEncodingException e) { throw error(logger, e.getMessage()); } try { msgWriter.write(branch, resource, out, targetClass); out.flush(); context.commitResource(logger, outStr).setPrivate(true); } catch (UnableToCompleteException e) { // msgWriter should have already logged an error message. // Keep going for now so we can find other errors. seenError = true; } } } } } if (seenError) { // If one of our generators had a fatal error, don't complete normally. throw new UnableToCompleteException(); } return packageName + "." + className; }
diff --git a/src/main/java/nl/surfnet/bod/nsi/v2/ConnectionsV2.java b/src/main/java/nl/surfnet/bod/nsi/v2/ConnectionsV2.java index 8e0bc4f6d..6ebe62e5e 100644 --- a/src/main/java/nl/surfnet/bod/nsi/v2/ConnectionsV2.java +++ b/src/main/java/nl/surfnet/bod/nsi/v2/ConnectionsV2.java @@ -1,73 +1,73 @@ /** * Copyright (c) 2012, SURFnet BV * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the SURFnet BV nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package nl.surfnet.bod.nsi.v2; import java.util.Arrays; import nl.surfnet.bod.domain.ConnectionV2; import nl.surfnet.bod.util.XmlUtils; import org.ogf.schemas.nsi._2013._04.connection.types.*; import org.ogf.schemas.nsi._2013._04.framework.types.TypeValuePairListType; import com.google.common.base.Function; import com.google.common.base.Joiner; public final class ConnectionsV2 { public static final Function<ConnectionV2, QuerySummaryResultType> toQuerySummaryResultType = new Function<ConnectionV2, QuerySummaryResultType>() { public QuerySummaryResultType apply(ConnectionV2 connection) { return new QuerySummaryResultType() .withRequesterNSA("requester") - .withCriteria(new ReservationConfirmCriteriaType() + .withCriteria(new QuerySummaryResultCriteriaType() .withBandwidth(connection.getDesiredBandwidth()) .withSchedule(new ScheduleType() .withEndTime(XmlUtils.toGregorianCalendar(connection.getEndTime().get())) .withStartTime(XmlUtils.toGregorianCalendar(connection.getStartTime().get()))) .withVersion(0) .withServiceAttributes(new TypeValuePairListType()) .withPath(new PathType() .withSourceSTP(toStpType(connection.getSourceStpId())) .withDestSTP(toStpType(connection.getDestinationStpId())) .withDirectionality(DirectionalityType.BIDIRECTIONAL))) .withConnectionId(connection.getConnectionId()) .withConnectionStates(new ConnectionStatesType() .withReservationState(connection.getReservationState()) .withLifecycleState(connection.getLifecycleState()) .withProvisionState(connection.getProvisionState()) .withDataPlaneStatus(new DataPlaneStatusType().withActive(false).withVersionConsistent(true).withVersion(0))); } }; private ConnectionsV2() { } public static StpType toStpType(String sourceStpId) { String[] parts = sourceStpId.split(":"); String networkId = Joiner.on(":").join(Arrays.copyOfRange(parts, 0, parts.length - 2)); return new StpType().withNetworkId(networkId).withLocalId(parts[parts.length - 1]); } }
true
true
public QuerySummaryResultType apply(ConnectionV2 connection) { return new QuerySummaryResultType() .withRequesterNSA("requester") .withCriteria(new ReservationConfirmCriteriaType() .withBandwidth(connection.getDesiredBandwidth()) .withSchedule(new ScheduleType() .withEndTime(XmlUtils.toGregorianCalendar(connection.getEndTime().get())) .withStartTime(XmlUtils.toGregorianCalendar(connection.getStartTime().get()))) .withVersion(0) .withServiceAttributes(new TypeValuePairListType()) .withPath(new PathType() .withSourceSTP(toStpType(connection.getSourceStpId())) .withDestSTP(toStpType(connection.getDestinationStpId())) .withDirectionality(DirectionalityType.BIDIRECTIONAL))) .withConnectionId(connection.getConnectionId()) .withConnectionStates(new ConnectionStatesType() .withReservationState(connection.getReservationState()) .withLifecycleState(connection.getLifecycleState()) .withProvisionState(connection.getProvisionState()) .withDataPlaneStatus(new DataPlaneStatusType().withActive(false).withVersionConsistent(true).withVersion(0))); }
public QuerySummaryResultType apply(ConnectionV2 connection) { return new QuerySummaryResultType() .withRequesterNSA("requester") .withCriteria(new QuerySummaryResultCriteriaType() .withBandwidth(connection.getDesiredBandwidth()) .withSchedule(new ScheduleType() .withEndTime(XmlUtils.toGregorianCalendar(connection.getEndTime().get())) .withStartTime(XmlUtils.toGregorianCalendar(connection.getStartTime().get()))) .withVersion(0) .withServiceAttributes(new TypeValuePairListType()) .withPath(new PathType() .withSourceSTP(toStpType(connection.getSourceStpId())) .withDestSTP(toStpType(connection.getDestinationStpId())) .withDirectionality(DirectionalityType.BIDIRECTIONAL))) .withConnectionId(connection.getConnectionId()) .withConnectionStates(new ConnectionStatesType() .withReservationState(connection.getReservationState()) .withLifecycleState(connection.getLifecycleState()) .withProvisionState(connection.getProvisionState()) .withDataPlaneStatus(new DataPlaneStatusType().withActive(false).withVersionConsistent(true).withVersion(0))); }
diff --git a/java/testing/org/apache/derbyTesting/functionTests/tests/derbynet/_Suite.java b/java/testing/org/apache/derbyTesting/functionTests/tests/derbynet/_Suite.java index 4a6313429..fd2dcd9fd 100644 --- a/java/testing/org/apache/derbyTesting/functionTests/tests/derbynet/_Suite.java +++ b/java/testing/org/apache/derbyTesting/functionTests/tests/derbynet/_Suite.java @@ -1,97 +1,98 @@ /* Derby - Class org.apache.derbyTesting.functionTests.tests.derbynet._Suite Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License */ package org.apache.derbyTesting.functionTests.tests.derbynet; import org.apache.derbyTesting.junit.BaseTestCase; import org.apache.derbyTesting.junit.Derby; import org.apache.derbyTesting.junit.JDBC; import junit.framework.Test; import junit.framework.TestSuite; /** * Suite to run all JUnit tests in this package: * org.apache.derbyTesting.functionTests.tests.derbynet * */ public class _Suite extends BaseTestCase { /** * Use suite method instead. */ private _Suite(String name) { super(name); } public static Test suite() throws Exception { TestSuite suite = new TestSuite("derbynet"); suite.addTest(PrepareStatementTest.suite()); suite.addTest(NetworkServerControlApiTest.suite()); suite.addTest(ShutDownDBWhenNSShutsDownTest.suite()); suite.addTest(DRDAProtocolTest.suite()); suite.addTest(ClientSideSystemPropertiesTest.suite()); suite.addTest(BadConnectionTest.suite()); suite.addTest(NetHarnessJavaTest.suite()); suite.addTest(SecureServerTest.suite()); suite.addTest(SysinfoTest.suite()); suite.addTest(SSLTest.suite()); suite.addTest(RuntimeInfoTest.suite()); suite.addTest(NetIjTest.suite()); suite.addTest(NSinSameJVMTest.suite()); suite.addTest(NetworkServerControlClientCommandTest.suite()); suite.addTest(ServerPropertiesTest.suite()); suite.addTest(LOBLocatorReleaseTest.suite()); suite.addTest(OutBufferedStreamTest.suite()); suite.addTest(GetCurrentPropertiesTest.suite()); suite.addTest(Utf8CcsidManagerTest.suite()); suite.addTest(Utf8CcsidManagerClientTest.suite()); // Disabled due to "java.sql.SQLSyntaxErrorException: The class // 'org.apache.derbyTesting.functionTests.tests.derbynet.checkSecMgr' // does not exist or is inaccessible. This can happen if the class is not public." // in the nightly tests with JDK 1.6 and jar files. //suite.addTest(CheckSecurityManager.suite()); if (JDBC.vmSupportsJDBC3()) { // this test refers to ConnectionPooledDataSource class // thus causing class not found exceptions with JSR169 suite.addTest(NSSecurityMechanismTest.suite()); // Test does not run on J2ME suite.addTest(DerbyNetNewServerTest.suite()); - suite.addTest(ProtocolTest.suite()); + // DERBY-2031: Temporarily disabled, investigating permission issue. + //suite.addTest(ProtocolTest.suite()); } // These tests references a client class directly // thus causing class not found exceptions if the // client code is not in the classpath. if (Derby.hasClient()) { suite.addTest(ByteArrayCombinerStreamTest.suite()); suite.addTest(SqlExceptionTest.suite()); } return suite; } }
true
true
public static Test suite() throws Exception { TestSuite suite = new TestSuite("derbynet"); suite.addTest(PrepareStatementTest.suite()); suite.addTest(NetworkServerControlApiTest.suite()); suite.addTest(ShutDownDBWhenNSShutsDownTest.suite()); suite.addTest(DRDAProtocolTest.suite()); suite.addTest(ClientSideSystemPropertiesTest.suite()); suite.addTest(BadConnectionTest.suite()); suite.addTest(NetHarnessJavaTest.suite()); suite.addTest(SecureServerTest.suite()); suite.addTest(SysinfoTest.suite()); suite.addTest(SSLTest.suite()); suite.addTest(RuntimeInfoTest.suite()); suite.addTest(NetIjTest.suite()); suite.addTest(NSinSameJVMTest.suite()); suite.addTest(NetworkServerControlClientCommandTest.suite()); suite.addTest(ServerPropertiesTest.suite()); suite.addTest(LOBLocatorReleaseTest.suite()); suite.addTest(OutBufferedStreamTest.suite()); suite.addTest(GetCurrentPropertiesTest.suite()); suite.addTest(Utf8CcsidManagerTest.suite()); suite.addTest(Utf8CcsidManagerClientTest.suite()); // Disabled due to "java.sql.SQLSyntaxErrorException: The class // 'org.apache.derbyTesting.functionTests.tests.derbynet.checkSecMgr' // does not exist or is inaccessible. This can happen if the class is not public." // in the nightly tests with JDK 1.6 and jar files. //suite.addTest(CheckSecurityManager.suite()); if (JDBC.vmSupportsJDBC3()) { // this test refers to ConnectionPooledDataSource class // thus causing class not found exceptions with JSR169 suite.addTest(NSSecurityMechanismTest.suite()); // Test does not run on J2ME suite.addTest(DerbyNetNewServerTest.suite()); suite.addTest(ProtocolTest.suite()); } // These tests references a client class directly // thus causing class not found exceptions if the // client code is not in the classpath. if (Derby.hasClient()) { suite.addTest(ByteArrayCombinerStreamTest.suite()); suite.addTest(SqlExceptionTest.suite()); } return suite; }
public static Test suite() throws Exception { TestSuite suite = new TestSuite("derbynet"); suite.addTest(PrepareStatementTest.suite()); suite.addTest(NetworkServerControlApiTest.suite()); suite.addTest(ShutDownDBWhenNSShutsDownTest.suite()); suite.addTest(DRDAProtocolTest.suite()); suite.addTest(ClientSideSystemPropertiesTest.suite()); suite.addTest(BadConnectionTest.suite()); suite.addTest(NetHarnessJavaTest.suite()); suite.addTest(SecureServerTest.suite()); suite.addTest(SysinfoTest.suite()); suite.addTest(SSLTest.suite()); suite.addTest(RuntimeInfoTest.suite()); suite.addTest(NetIjTest.suite()); suite.addTest(NSinSameJVMTest.suite()); suite.addTest(NetworkServerControlClientCommandTest.suite()); suite.addTest(ServerPropertiesTest.suite()); suite.addTest(LOBLocatorReleaseTest.suite()); suite.addTest(OutBufferedStreamTest.suite()); suite.addTest(GetCurrentPropertiesTest.suite()); suite.addTest(Utf8CcsidManagerTest.suite()); suite.addTest(Utf8CcsidManagerClientTest.suite()); // Disabled due to "java.sql.SQLSyntaxErrorException: The class // 'org.apache.derbyTesting.functionTests.tests.derbynet.checkSecMgr' // does not exist or is inaccessible. This can happen if the class is not public." // in the nightly tests with JDK 1.6 and jar files. //suite.addTest(CheckSecurityManager.suite()); if (JDBC.vmSupportsJDBC3()) { // this test refers to ConnectionPooledDataSource class // thus causing class not found exceptions with JSR169 suite.addTest(NSSecurityMechanismTest.suite()); // Test does not run on J2ME suite.addTest(DerbyNetNewServerTest.suite()); // DERBY-2031: Temporarily disabled, investigating permission issue. //suite.addTest(ProtocolTest.suite()); } // These tests references a client class directly // thus causing class not found exceptions if the // client code is not in the classpath. if (Derby.hasClient()) { suite.addTest(ByteArrayCombinerStreamTest.suite()); suite.addTest(SqlExceptionTest.suite()); } return suite; }
diff --git a/src/main/java/ch/tkuhn/hashuri/rdf/StatementComparator.java b/src/main/java/ch/tkuhn/hashuri/rdf/StatementComparator.java index 825c9fd..0d1e193 100644 --- a/src/main/java/ch/tkuhn/hashuri/rdf/StatementComparator.java +++ b/src/main/java/ch/tkuhn/hashuri/rdf/StatementComparator.java @@ -1,103 +1,105 @@ package ch.tkuhn.hashuri.rdf; import java.util.Comparator; import org.openrdf.model.BNode; import org.openrdf.model.Literal; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; public class StatementComparator implements Comparator<Statement> { public StatementComparator() { } @Override public int compare(Statement st1, Statement st2) { int c; c = compareContext(st1, st2); if (c != 0) return c; c = compareSubject(st1, st2); if (c != 0) return c; c = comparePredicate(st1, st2); if (c != 0) return c; return compareObject(st1, st2); } private int compareContext(Statement st1, Statement st2) { Resource r1 = st1.getContext(); Resource r2 = st2.getContext(); if (r1 == null && r2 == null) { return 0; } else if (r1 == null && r2 != null) { return -1; } else if (r1 != null && r2 == null) { return 1; } return compareResource(r1, r2); } private int compareSubject(Statement st1, Statement st2) { return compareResource(st1.getSubject(), st2.getSubject()); } private int comparePredicate(Statement st1, Statement st2) { return compareURIs(st1.getPredicate(), st2.getPredicate()); } private int compareObject(Statement st1, Statement st2) { Value v1 = st1.getObject(); Value v2 = st2.getObject(); if (v1 instanceof Literal && !(v2 instanceof Literal)) { return 1; } else if (!(v1 instanceof Literal) && v2 instanceof Literal) { return -1; } else if (v1 instanceof Literal) { return compareLiteral((Literal) v1, (Literal) v2); } else { return compareResource((Resource) v1, (Resource) v2); } } private int compareResource(Resource r1, Resource r2) { if (r1 instanceof BNode) { throw new RuntimeException("Unexpected blank node"); } else { return compareURIs((URI) r1, (URI) r2); } } private int compareLiteral(Literal l1, Literal l2) { String s1 = l1.stringValue(); String s2 = l2.stringValue(); if (!s1.equals(s2)) { return s1.compareTo(s2); } - s1 = l1.getDatatype().toString(); - s2 = l2.getDatatype().toString(); + s1 = null; + s2 = null; + if (l1.getDatatype() != null) s1 = l1.getDatatype().toString(); + if (l2.getDatatype() != null) s2 = l2.getDatatype().toString(); if (s1 == null && s2 != null) { return -1; } else if (s1 != null && s2 == null) { return 1; } else if (s1 != null && !s1.equals(s2)) { return s1.compareTo(s2); } s1 = l1.getLanguage(); s2 = l2.getLanguage(); if (s1 == null && s2 != null) { return -1; } else if (s1 != null && s2 == null) { return 1; } else if (s1 != null && !s1.equals(s2)) { return s1.compareTo(s2); } return 0; } private int compareURIs(URI uri1, URI uri2) { return uri1.toString().compareTo(uri2.toString()); } }
true
true
private int compareLiteral(Literal l1, Literal l2) { String s1 = l1.stringValue(); String s2 = l2.stringValue(); if (!s1.equals(s2)) { return s1.compareTo(s2); } s1 = l1.getDatatype().toString(); s2 = l2.getDatatype().toString(); if (s1 == null && s2 != null) { return -1; } else if (s1 != null && s2 == null) { return 1; } else if (s1 != null && !s1.equals(s2)) { return s1.compareTo(s2); } s1 = l1.getLanguage(); s2 = l2.getLanguage(); if (s1 == null && s2 != null) { return -1; } else if (s1 != null && s2 == null) { return 1; } else if (s1 != null && !s1.equals(s2)) { return s1.compareTo(s2); } return 0; }
private int compareLiteral(Literal l1, Literal l2) { String s1 = l1.stringValue(); String s2 = l2.stringValue(); if (!s1.equals(s2)) { return s1.compareTo(s2); } s1 = null; s2 = null; if (l1.getDatatype() != null) s1 = l1.getDatatype().toString(); if (l2.getDatatype() != null) s2 = l2.getDatatype().toString(); if (s1 == null && s2 != null) { return -1; } else if (s1 != null && s2 == null) { return 1; } else if (s1 != null && !s1.equals(s2)) { return s1.compareTo(s2); } s1 = l1.getLanguage(); s2 = l2.getLanguage(); if (s1 == null && s2 != null) { return -1; } else if (s1 != null && s2 == null) { return 1; } else if (s1 != null && !s1.equals(s2)) { return s1.compareTo(s2); } return 0; }
diff --git a/BlueFinderRS/src/knn/clean/BlueFinderEvaluation.java b/BlueFinderRS/src/knn/clean/BlueFinderEvaluation.java index 06aa21e..98bcfac 100644 --- a/BlueFinderRS/src/knn/clean/BlueFinderEvaluation.java +++ b/BlueFinderRS/src/knn/clean/BlueFinderEvaluation.java @@ -1,140 +1,140 @@ package knn.clean; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.TreeMap; import strategies.LastCategoryGeneralization; import knn.Instance; import knn.distance.SemanticPair; import db.MysqlIndexConnection; import db.WikipediaConnector; import dbpedia.similarityStrategies.ValueComparator; /**This class compute the evaluation for one PathIndex. The evaluation is the one that is * included in the journal article. * * @author dtorres * */ public class BlueFinderEvaluation { private KNN knn; public BlueFinderEvaluation(KNN knn){ this.knn=knn; } //private void processTest(String piaIndexBase, String typesTable, // int kValue, int testRowsNumber, String resultTableName) // throws ClassNotFoundException, SQLException { private void processTest(int proportionOfConnectedPairs, int kValue, int testRowsNumber, String resultTableName) throws ClassNotFoundException, SQLException { ResultSet resultSet = WikipediaConnector.getRandomProportionOfConnectedPairs(proportionOfConnectedPairs); String relatedUFrom = "u_from=0 "; String relatedString = ""; while (resultSet.next()) { long time_start, time_end; time_start = System.currentTimeMillis(); SemanticPair disconnectedPair = this.knn.generateSemanticPair(resultSet.getString("page"), resultSet.getLong("id")); List<Instance> kNearestNeighbors = this.knn.getKNearestNeighbors(kValue, disconnectedPair); SemanticPairInstance disconnectedInstance = new SemanticPairInstance(0, disconnectedPair); kNearestNeighbors.remove(disconnectedInstance); List<String> knnResults = new ArrayList<String>(); for (Instance neighbor : kNearestNeighbors) { relatedUFrom = relatedUFrom + "or u_from = " + neighbor.getId() + " "; relatedString = relatedString + "(" + neighbor.getDistance() + ") " + neighbor.getResource() + " "; Statement st = WikipediaConnector.getResultsConnection().createStatement(); String queryFixed = "SELECT v_to, count(v_to) suma,V.path from UxV, V_Normalized V where v_to=V.id and ("+ relatedUFrom +") group by v_to order by suma desc"; ResultSet paths = st.executeQuery(queryFixed); TreeMap<String, Integer> map = this.genericPath(paths, knnResults.size()+1); // for (String pathGen : map.keySet()) { // System.out.println(map); knnResults.add(map.toString()); // System.out.println("end ---- k="+kvalue); } time_end = System.currentTimeMillis(); // Insert statem - String insertSentence = "INSERT INTO `dbresearch`.`"+ resultTableName + "` (`v_to`, `related_resources`,`1path`, `2path`, `3path`, `4path`, `5path`, `6path`, `7path`, `8path`, `9path`, `10path`,`time`)" + String insertSentence = "INSERT INTO "+ resultTableName + "` (`v_to`, `related_resources`,`1path`, `2path`, `3path`, `4path`, `5path`, `6path`, `7path`, `8path`, `9path`, `10path`,`time`)" + "VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"; - PreparedStatement st = connection.prepareStatement(insertSentence); + PreparedStatement st = WikipediaConnector.getResultsConnection().prepareStatement(insertSentence); st.setString(1, resultSet.getString("resource")+" "+resultSet.getInt("path_query")); st.setString(2, relatedString); int i = 3; for (String string : knnResults) { st.setString(i, string); i++; } st.setLong(13, time_end - time_start); st.executeUpdate(); - relatedVTo = "v_to=0 "; + relatedUFrom = "u_from=0 "; relatedString = ""; } } protected TreeMap<String,Integer> genericPath(ResultSet paths, int kValue) throws SQLException { HashMap<String, Integer> pathDictionary = new HashMap<String, Integer>(); ValueComparator bvc = new ValueComparator(pathDictionary); TreeMap<String,Integer> sorted_map = new TreeMap<String,Integer>(bvc); LastCategoryGeneralization cg = new LastCategoryGeneralization(); while(paths.next()){ //SELECT v_to, count(v_to) suma,V.path from UxV, V_Normalized V String path=paths.getString("path"); path=cg.generalizePathQuery(path); int suma = paths.getInt("suma"); // if((!path.contains("Articles_") || path.contains("Articles_li�s") ) && !path.contains("All_Wikipedia_") && !path.contains("Wikipedia_") && !path.contains("Non-free") && !path.contains("All_pages_") && !path.contains("All_non") ){ if(pathDictionary.get(path)==null){ if(suma==kValue){ //all the cases belongs to this path query suma=suma+1000; } pathDictionary.put(path, suma); }else{ suma+=pathDictionary.get(path); pathDictionary.put(path, suma); } } } //sorted_map.putAll(pathDictionary); for (String path : pathDictionary.keySet()) { Integer suma = pathDictionary.get(path); sorted_map.put(path,suma); } return sorted_map; } }
false
true
private void processTest(int proportionOfConnectedPairs, int kValue, int testRowsNumber, String resultTableName) throws ClassNotFoundException, SQLException { ResultSet resultSet = WikipediaConnector.getRandomProportionOfConnectedPairs(proportionOfConnectedPairs); String relatedUFrom = "u_from=0 "; String relatedString = ""; while (resultSet.next()) { long time_start, time_end; time_start = System.currentTimeMillis(); SemanticPair disconnectedPair = this.knn.generateSemanticPair(resultSet.getString("page"), resultSet.getLong("id")); List<Instance> kNearestNeighbors = this.knn.getKNearestNeighbors(kValue, disconnectedPair); SemanticPairInstance disconnectedInstance = new SemanticPairInstance(0, disconnectedPair); kNearestNeighbors.remove(disconnectedInstance); List<String> knnResults = new ArrayList<String>(); for (Instance neighbor : kNearestNeighbors) { relatedUFrom = relatedUFrom + "or u_from = " + neighbor.getId() + " "; relatedString = relatedString + "(" + neighbor.getDistance() + ") " + neighbor.getResource() + " "; Statement st = WikipediaConnector.getResultsConnection().createStatement(); String queryFixed = "SELECT v_to, count(v_to) suma,V.path from UxV, V_Normalized V where v_to=V.id and ("+ relatedUFrom +") group by v_to order by suma desc"; ResultSet paths = st.executeQuery(queryFixed); TreeMap<String, Integer> map = this.genericPath(paths, knnResults.size()+1); // for (String pathGen : map.keySet()) { // System.out.println(map); knnResults.add(map.toString()); // System.out.println("end ---- k="+kvalue); } time_end = System.currentTimeMillis(); // Insert statem String insertSentence = "INSERT INTO `dbresearch`.`"+ resultTableName + "` (`v_to`, `related_resources`,`1path`, `2path`, `3path`, `4path`, `5path`, `6path`, `7path`, `8path`, `9path`, `10path`,`time`)" + "VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"; PreparedStatement st = connection.prepareStatement(insertSentence); st.setString(1, resultSet.getString("resource")+" "+resultSet.getInt("path_query")); st.setString(2, relatedString); int i = 3; for (String string : knnResults) { st.setString(i, string); i++; } st.setLong(13, time_end - time_start); st.executeUpdate(); relatedVTo = "v_to=0 "; relatedString = ""; } }
private void processTest(int proportionOfConnectedPairs, int kValue, int testRowsNumber, String resultTableName) throws ClassNotFoundException, SQLException { ResultSet resultSet = WikipediaConnector.getRandomProportionOfConnectedPairs(proportionOfConnectedPairs); String relatedUFrom = "u_from=0 "; String relatedString = ""; while (resultSet.next()) { long time_start, time_end; time_start = System.currentTimeMillis(); SemanticPair disconnectedPair = this.knn.generateSemanticPair(resultSet.getString("page"), resultSet.getLong("id")); List<Instance> kNearestNeighbors = this.knn.getKNearestNeighbors(kValue, disconnectedPair); SemanticPairInstance disconnectedInstance = new SemanticPairInstance(0, disconnectedPair); kNearestNeighbors.remove(disconnectedInstance); List<String> knnResults = new ArrayList<String>(); for (Instance neighbor : kNearestNeighbors) { relatedUFrom = relatedUFrom + "or u_from = " + neighbor.getId() + " "; relatedString = relatedString + "(" + neighbor.getDistance() + ") " + neighbor.getResource() + " "; Statement st = WikipediaConnector.getResultsConnection().createStatement(); String queryFixed = "SELECT v_to, count(v_to) suma,V.path from UxV, V_Normalized V where v_to=V.id and ("+ relatedUFrom +") group by v_to order by suma desc"; ResultSet paths = st.executeQuery(queryFixed); TreeMap<String, Integer> map = this.genericPath(paths, knnResults.size()+1); // for (String pathGen : map.keySet()) { // System.out.println(map); knnResults.add(map.toString()); // System.out.println("end ---- k="+kvalue); } time_end = System.currentTimeMillis(); // Insert statem String insertSentence = "INSERT INTO "+ resultTableName + "` (`v_to`, `related_resources`,`1path`, `2path`, `3path`, `4path`, `5path`, `6path`, `7path`, `8path`, `9path`, `10path`,`time`)" + "VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"; PreparedStatement st = WikipediaConnector.getResultsConnection().prepareStatement(insertSentence); st.setString(1, resultSet.getString("resource")+" "+resultSet.getInt("path_query")); st.setString(2, relatedString); int i = 3; for (String string : knnResults) { st.setString(i, string); i++; } st.setLong(13, time_end - time_start); st.executeUpdate(); relatedUFrom = "u_from=0 "; relatedString = ""; } }
diff --git a/src/main/java/org/linkedgov/questions/services/impl/QueryDataServiceImpl.java b/src/main/java/org/linkedgov/questions/services/impl/QueryDataServiceImpl.java index 7a23210..4b05d66 100644 --- a/src/main/java/org/linkedgov/questions/services/impl/QueryDataServiceImpl.java +++ b/src/main/java/org/linkedgov/questions/services/impl/QueryDataServiceImpl.java @@ -1,337 +1,337 @@ package org.linkedgov.questions.services.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.WordUtils; import org.linkedgov.questions.model.Pair; import org.linkedgov.questions.model.Query; import org.linkedgov.questions.model.QuestionType; import org.linkedgov.questions.model.SparqlUtils; import org.linkedgov.questions.model.Triple; import org.linkedgov.questions.services.QueryDataService; import org.linkedgov.questions.services.SparqlDao; import org.slf4j.Logger; import uk.me.mmt.sprotocol.BNode; import uk.me.mmt.sprotocol.IRI; import uk.me.mmt.sprotocol.Literal; import uk.me.mmt.sprotocol.SelectResult; import uk.me.mmt.sprotocol.SelectResultSet; import uk.me.mmt.sprotocol.SparqlResource; /** * This class generates the object needed by the dataTable component * * @author Luke Wilson-Mawer <a href="http://viscri.co.uk/">Viscri</a> and * @author <a href="http://mmt.me.uk/foaf.rdf#mischa">Mischa Tuffield</a> for LinkedGov * */ public class QueryDataServiceImpl implements QueryDataService { /** * Used to get the reliability score */ private static final String GET_RELIABILITY = "SELECT DISTINCT ?rel WHERE " + "{<%s> <http://data.linkedgov.org/ns#reliability> ?rel } LIMIT 1 "; private static final String XSD_INTEGER = "http://www.w3.org/2001/XMLSchema#integer"; /** * To do the actual querying with. */ private final SparqlDao sparqlDao; /** * To log stuff with. */ private final Logger log; /** * Automatically called by tapestry when instantiating the service, which is a singleton. */ public QueryDataServiceImpl(SparqlDao sparqlDao, Logger log){ this.sparqlDao = sparqlDao; this.log = log; } /** * Get results for the user's question. * * @param Query object representing a user's question. * @return a list of triples representing the answer to the question. */ public List<Triple> executeQuery(Query query) { return executeQuery(query, null, null, null); } /** * Converts a result into a triple. * * @param head a list of the variable names in the results. * @param result the result to convert. * @return the triple that represents the result. */ private Triple resultToTriple(List<String> head, SelectResult result) { final Triple triple = new Triple(); for (String variable : head) { final SparqlResource resource = result.getResult().get(variable); final Pair<SparqlResource,String> sub = new Pair<SparqlResource,String>(); final Pair<SparqlResource,String> pred = new Pair<SparqlResource,String>(); final Pair<SparqlResource,String> obj = new Pair<SparqlResource,String>(); if (variable.equals("sub")) { sub.setFirst(resource); triple.setSubject(sub); } else if (variable.equals("pred")) { pred.setFirst(resource); triple.setPredicate(pred); } else if (variable.equals("obj")) { obj.setFirst(resource); triple.setObject(obj); } else if (variable.equals("cnt")) { sub.setFirst(resource); triple.setSubject(sub); } else if (variable.equals("slabel") && resource != null) { sub.setFirst(resource); triple.setSubject(sub); } else if (variable.equals("plabel") && resource != null) { resource.setValue(WordUtils.capitalize(resource.getValue())); pred.setFirst(resource); triple.setPredicate(pred); } else if (variable.equals("olabel") && resource != null) { obj.setFirst(resource); triple.setObject(obj); } } return triple; } /** * This function shows how if a URI of a certain rdf:type is returned it can be * implemented as a special case */ private String makeAddressPretty(List<Triple> triples) { String street = ""; String region = ""; String locality = ""; String postcode = ""; for (Triple triple : triples) { if (triple.getPredicate().getFirst().getValue().equals("http://www.w3.org/2006/vcard/ns#street-address")) { street = triple.getObject().getFirst().getValue(); } else if (triple.getPredicate().getFirst().getValue().equals("http://www.w3.org/2006/vcard/ns#region")) { region = triple.getObject().getFirst().getValue(); } else if (triple.getPredicate().getFirst().getValue().equals("http://www.w3.org/2006/vcard/ns#locality")) { locality = triple.getObject().getFirst().getValue(); } else if (triple.getPredicate().getFirst().getValue().equals("http://www.w3.org/2006/vcard/ns#postcode")) { postcode = triple.getObject().getFirst().getValue().substring(triple.getObject().getFirst().getValue().lastIndexOf("/")+1); } } String pretty = StringUtils.strip(street)+", "+StringUtils.strip(region)+", "+StringUtils.strip(locality)+", "+StringUtils.strip(postcode); pretty.replaceAll(", ,", ""); return pretty; } public List<Triple> executeQuery(Query query, Integer limit, Integer offset, String orderBy) { final List<Triple> triples = new ArrayList<Triple>(); if (!query.isNull()) { final String sparqlString = query.toSparqlString(); log.info("SPARQL ASKED:{}", sparqlString); log.info("QUESTION ASKED:{}", query.toString()); final SelectResultSet results = sparqlDao.executeQuery(sparqlString, limit, offset, orderBy); for (SelectResult result : results.getResults()) { final Triple triple = resultToTriple(results.getHead(), result); triples.add(triple); } } //Specialising bnode.size = 1 and where we define vcard#Address functionality final List<Triple> finalTriples = new ArrayList<Triple>(); for (Triple triple : triples) { if (triple.getObject().getFirst() instanceof IRI) { List<Triple> iriTriples = executeIRIQuery(triple.getObject().getFirst().getValue()); - System.err.println("This size of the triples for a Given IRI is"+iriTriples.size()); + log.info("This size of the triples for a Given IRI is"+iriTriples.size()); boolean isAddress = false; for (Triple row : iriTriples) { if (row.getPredicate().getFirst().getValue().equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#type") && row.getObject().getFirst().getValue().equals("http://www.w3.org/2006/vcard/ns#Address")) { isAddress = true; break; } } //Am now handling the special cases here if (isAddress) { Triple newTriple = triple; newTriple.getObject().getFirst().setValue(makeAddressPretty(iriTriples)); finalTriples.add(newTriple); } else { finalTriples.add(triple); } } else if (triple.getObject().getFirst() instanceof BNode) { List<Triple> bnodeTriples = executeBnodeQuery(triple.getObject().getFirst().getValue()); if (bnodeTriples.size() == 1) { Triple newTriple = triple; newTriple.getObject().getFirst().setValue(bnodeTriples.get(0).getObject().getFirst().getValue()); finalTriples.add(newTriple); } else { finalTriples.add(triple); } } else { finalTriples.add(triple); } } return finalTriples; } /** * Executes a count for this query. If the query itself is a count, it returns 1. */ public int executeCountForQuery(Query query, boolean forPagination) { if (QuestionType.COUNT.equals(query.getQuestionType())) { return 1; } if (query.isNull()) { return 0; } final String countSparqlString = query.toSparqlString(QuestionType.COUNT, forPagination, false); final SelectResultSet results = sparqlDao.executeQuery(countSparqlString); if (results.getResults().isEmpty()) { return 0; } final String countLabel = results.getHead().get(0); final SelectResult firstResult = results.getResults().get(0); final String count = firstResult.getResult().get(countLabel).getValue(); if(count == null){ return 0; } return Integer.valueOf(count); } /** * This get all of the dataset's used to answer a query created by the user */ public Map<String,String> executeGetAllGraphNames(Query query) { final String queryGraphs = query.toSparqlString(QuestionType.SELECT, false, true); final SelectResultSet graphs = sparqlDao.executeQuery(queryGraphs); Map<String,String> retValues = new HashMap<String,String>(); for (SelectResult result : graphs.getResults()) { final SparqlResource element = result.getResult().get("g"); if (result.getResult().get("glabel") != null) { retValues.put(element.getValue(),result.getResult().get("glabel").getValue()); } else { retValues.put(element.getValue(),element.getValue()); } } return retValues; } /** * This get the reliability score by querying the knowledge base * * @return the average reliability score of the graphs or 0 */ public int executeReliabilityScore(Map<String,String> graphs) { SelectResultSet results = new SelectResultSet(); int reliability = 0; int count = 0; for (String dataSet : graphs.keySet()) { String query = String.format(GET_RELIABILITY, dataSet); results = sparqlDao.executeQuery(query); for (SelectResult result : results.getResults()) { SparqlResource element = result.getResult().get("rel"); if (element instanceof Literal) { if (((Literal) element).getDatatype().equals(XSD_INTEGER)) { if (SparqlUtils.isInteger(element.getValue())) { reliability = reliability + Integer.parseInt(element.getValue()); count++; } } } } } if (reliability > 0 && count > 0) { reliability = reliability / count; } return reliability; } /** * * @param an iri is passed in, this is used to perform the special case's * the only special case currently implemented is the vcard#Address * @return a list of triples */ public List<Triple> executeIRIQuery(String iri) { StringBuilder query = new StringBuilder(); query.append("SELECT DISTINCT (<"); query.append(iri); query.append("> as ?sub) ?pred ?obj "); query.append("WHERE { <"); query.append(iri); query.append("> ?pred ?obj . "); query.append("}"); final String sparqlString = query.toString(); log.info("SPARQL ASKED to grab IRI Info:{}", sparqlString); final SelectResultSet results = sparqlDao.executeQuery(sparqlString); final List<Triple> triples = new ArrayList<Triple>(); for (SelectResult result : results.getResults()) { final Triple triple = resultToTriple(results.getHead(), result); triples.add(triple); } return triples; } /** * This function is used to return triples about a given Bnode * This is used to fill out the Grid Component * @param a bnode id is passed in, this is used to perform the special case's * the only special case currently implemented is the "single bnode case" * @return a list of triples */ public List<Triple> executeBnodeQuery(String bnode) { StringBuilder query = new StringBuilder(); query.append("SELECT DISTINCT (<bnode:"); query.append(bnode); query.append("> as ?sub) ?pred ?obj ?slabel ?plabel ?olabel "); query.append("WHERE { <bnode:"); query.append(bnode); query.append("> ?pred ?obj . "); query.append("OPTIONAL {<bnode:"); query.append(bnode); query.append("> <http://www.w3.org/2000/01/rdf-schema#label> ?slabel } . "); query.append("OPTIONAL {?pred <http://www.w3.org/2000/01/rdf-schema#label> ?plabel } . "); query.append("OPTIONAL {?obj <http://www.w3.org/2000/01/rdf-schema#label> ?olabel } . "); query.append("}"); final String sparqlString = query.toString(); log.info("SPARQL ASKED to grab Bnode Info:{}", sparqlString); final SelectResultSet results = sparqlDao.executeQuery(sparqlString); final List<Triple> triples = new ArrayList<Triple>(); for (SelectResult result : results.getResults()) { final Triple triple = resultToTriple(results.getHead(), result); triples.add(triple); } return triples; } }
true
true
public List<Triple> executeQuery(Query query, Integer limit, Integer offset, String orderBy) { final List<Triple> triples = new ArrayList<Triple>(); if (!query.isNull()) { final String sparqlString = query.toSparqlString(); log.info("SPARQL ASKED:{}", sparqlString); log.info("QUESTION ASKED:{}", query.toString()); final SelectResultSet results = sparqlDao.executeQuery(sparqlString, limit, offset, orderBy); for (SelectResult result : results.getResults()) { final Triple triple = resultToTriple(results.getHead(), result); triples.add(triple); } } //Specialising bnode.size = 1 and where we define vcard#Address functionality final List<Triple> finalTriples = new ArrayList<Triple>(); for (Triple triple : triples) { if (triple.getObject().getFirst() instanceof IRI) { List<Triple> iriTriples = executeIRIQuery(triple.getObject().getFirst().getValue()); System.err.println("This size of the triples for a Given IRI is"+iriTriples.size()); boolean isAddress = false; for (Triple row : iriTriples) { if (row.getPredicate().getFirst().getValue().equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#type") && row.getObject().getFirst().getValue().equals("http://www.w3.org/2006/vcard/ns#Address")) { isAddress = true; break; } } //Am now handling the special cases here if (isAddress) { Triple newTriple = triple; newTriple.getObject().getFirst().setValue(makeAddressPretty(iriTriples)); finalTriples.add(newTriple); } else { finalTriples.add(triple); } } else if (triple.getObject().getFirst() instanceof BNode) { List<Triple> bnodeTriples = executeBnodeQuery(triple.getObject().getFirst().getValue()); if (bnodeTriples.size() == 1) { Triple newTriple = triple; newTriple.getObject().getFirst().setValue(bnodeTriples.get(0).getObject().getFirst().getValue()); finalTriples.add(newTriple); } else { finalTriples.add(triple); } } else { finalTriples.add(triple); } } return finalTriples; }
public List<Triple> executeQuery(Query query, Integer limit, Integer offset, String orderBy) { final List<Triple> triples = new ArrayList<Triple>(); if (!query.isNull()) { final String sparqlString = query.toSparqlString(); log.info("SPARQL ASKED:{}", sparqlString); log.info("QUESTION ASKED:{}", query.toString()); final SelectResultSet results = sparqlDao.executeQuery(sparqlString, limit, offset, orderBy); for (SelectResult result : results.getResults()) { final Triple triple = resultToTriple(results.getHead(), result); triples.add(triple); } } //Specialising bnode.size = 1 and where we define vcard#Address functionality final List<Triple> finalTriples = new ArrayList<Triple>(); for (Triple triple : triples) { if (triple.getObject().getFirst() instanceof IRI) { List<Triple> iriTriples = executeIRIQuery(triple.getObject().getFirst().getValue()); log.info("This size of the triples for a Given IRI is"+iriTriples.size()); boolean isAddress = false; for (Triple row : iriTriples) { if (row.getPredicate().getFirst().getValue().equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#type") && row.getObject().getFirst().getValue().equals("http://www.w3.org/2006/vcard/ns#Address")) { isAddress = true; break; } } //Am now handling the special cases here if (isAddress) { Triple newTriple = triple; newTriple.getObject().getFirst().setValue(makeAddressPretty(iriTriples)); finalTriples.add(newTriple); } else { finalTriples.add(triple); } } else if (triple.getObject().getFirst() instanceof BNode) { List<Triple> bnodeTriples = executeBnodeQuery(triple.getObject().getFirst().getValue()); if (bnodeTriples.size() == 1) { Triple newTriple = triple; newTriple.getObject().getFirst().setValue(bnodeTriples.get(0).getObject().getFirst().getValue()); finalTriples.add(newTriple); } else { finalTriples.add(triple); } } else { finalTriples.add(triple); } } return finalTriples; }
diff --git a/src/com/icecondor/nest/Pigeon.java b/src/com/icecondor/nest/Pigeon.java index 44f9682..48170c7 100644 --- a/src/com/icecondor/nest/Pigeon.java +++ b/src/com/icecondor/nest/Pigeon.java @@ -1,528 +1,530 @@ package com.icecondor.nest; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import net.oauth.OAuth; import net.oauth.OAuthAccessor; import net.oauth.OAuthException; import net.oauth.OAuthMessage; import net.oauth.client.OAuthClient; import net.oauth.client.httpclient4.HttpClient4; import net.oauth.client.httpclient4.HttpClientPool; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.params.AllClientPNames; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.media.MediaPlayer; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.preference.PreferenceManager; import android.util.Log; import com.icecondor.nest.db.GeoRss; import com.icecondor.nest.db.LocationStorageProviders; //look at android.permission.RECEIVE_BOOT_COMPLETED public class Pigeon extends Service implements Constants, LocationListener, SharedPreferences.OnSharedPreferenceChangeListener { private Timer heartbeat_timer; private Timer rss_timer; private Timer push_queue_timer; //private Timer wifi_scan_timer = new Timer(); static final String appTag = "Pigeon"; boolean on_switch = false; private Location last_recorded_fix, last_pushed_fix, last_local_fix; long last_pushed_time; int last_fix_http_status; Notification ongoing_notification; NotificationManager notificationManager; LocationManager locationManager; WifiManager wifiManager; PendingIntent contentIntent; SharedPreferences settings; GeoRss rssdb; MediaPlayer mp; private TimerTask heartbeatTask; DefaultHttpClient httpClient; OAuthClient oclient; public void onCreate() { Log.i(appTag, "*** service created."); super.onCreate(); /* Database */ rssdb = new GeoRss(this); rssdb.open(); rssdb.log("Pigon created"); /* GPS */ locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); Log.i(appTag, "GPS provider enabled: "+locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)); last_local_fix = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); Log.i(appTag, "NETWORK provider enabled: "+locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)); Location last_network_fix = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); - Log.i(appTag, "Last known NETWORK fix: "+last_network_fix+" "+Util.DateTimeIso8601(last_network_fix.getTime())); - if (last_local_fix == null) { // fall back onto the network location - last_local_fix = last_network_fix; + if (last_local_fix == null) { + if(last_network_fix != null) { + last_local_fix = last_network_fix; // fall back onto the network location + Log.i(appTag, "Last known NETWORK fix: "+last_network_fix+" "+Util.DateTimeIso8601(last_network_fix.getTime())); + } } else { Log.i(appTag, "Last known GPS fix: "+last_local_fix+" "+Util.DateTimeIso8601(last_local_fix.getTime())); } /* WIFI */ wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); /* Notifications */ notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Start.class), 0); CharSequence text = getText(R.string.status_started); ongoing_notification = new Notification(R.drawable.condorhead_statusbar, text, System .currentTimeMillis()); ongoing_notification.flags = ongoing_notification.flags ^ Notification.FLAG_ONGOING_EVENT; ongoing_notification.setLatestEventInfo(this, "IceCondor", "", contentIntent); /* Preferences */ settings = PreferenceManager.getDefaultSharedPreferences(this); settings.registerOnSharedPreferenceChangeListener(this); on_switch = settings.getBoolean(SETTING_PIGEON_TRANSMITTING, false); if (on_switch) { //startForeground(1, ongoing_notification); startLocationUpdates(); } /* Sound */ mp = MediaPlayer.create(this, R.raw.beep); startHeartbeatTimer(); startRssTimer(); startPushQueueTimer(); /* Apache HTTP Monstrosity*/ httpClient = new DefaultHttpClient(); httpClient.getParams().setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 15 *1000); httpClient.getParams().setIntParameter(AllClientPNames.SO_TIMEOUT, 30 *1000); oclient = new OAuthClient(new HttpClient4()); } public void onStart(Intent start, int key) { super.onStart(start,key); rssdb.log("Pigon started"); } public void onDestroy() { stopRssTimer(); stopLocationUpdates(); stopPushQueueTimer(); rssdb.log("Pigon destroyed"); rssdb.close(); notificationManager.cancel(1); } private void notificationStatusUpdate(String msg) { ongoing_notification.setLatestEventInfo(this, "IceCondor", msg, contentIntent); ongoing_notification.when = System.currentTimeMillis(); notificationManager.notify(1, ongoing_notification); } private void notification(String msg) { Notification notification = new Notification(R.drawable.condorhead_statusbar, msg, System.currentTimeMillis()); // a contentView error is thrown if this line is not here notification.setLatestEventInfo(this, "IceCondor Notice", msg, contentIntent); notificationManager.notify(2, notification); } private void notificationFlash(String msg) { notification(msg); notificationManager.cancel(2); } private void startLocationUpdates() { long record_frequency = Long.decode(settings.getString(SETTING_TRANSMISSION_FREQUENCY, "300000")); rssdb.log("requesting Location Updates every "+ Util.millisecondsToWords(record_frequency)); locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, record_frequency, 0.0F, this); // Network provider takes no extra power but the accuracy is // too low to be useful. //locationManager.requestLocationUpdates( // LocationManager.NETWORK_PROVIDER, 60000L, 0.0F, pigeon); // Log.i(appTag, "kicking off wifi scan timer"); // wifi_scan_timer.scheduleAtFixedRate( // new TimerTask() { // public void run() { // Log.i(appTag, "wifi: start scan (enabled:"+wifiManager.isWifiEnabled()+")"); // wifiManager.startScan(); // } // }, 0, 60000); } private void stopLocationUpdates() { rssdb.log("pigeon: stopping GPS updates"); locationManager.removeUpdates(this); } @Override public IBinder onBind(Intent intent) { rssdb.log("Pigeon onBind for "+intent.getAction()); return pigeonBinder; } @Override public void onRebind(Intent intent) { rssdb.log("pigeon: onReBind for "+intent.getAction()); } @Override public void onLowMemory() { rssdb.log("onLowMemory"); } @Override public boolean onUnbind(Intent intent) { Log.i(appTag, "onUnbind for "+intent.getAction()); rssdb.log("pigeon: onUnbind for "+intent.getAction()); return false; } public void pushQueue() { Timer push_queue_timer_single = new Timer("Push Queue Single Timer"); push_queue_timer_single.schedule(new PushQueueTask(), 0); } class PushQueueTask extends TimerTask { public void run() { Cursor oldest; rssdb.log("** Starting queue push of size "+rssdb.countPositionQueueRemaining()); if ((oldest = rssdb.oldestUnpushedLocationQueue()).getCount() > 0) { int id = oldest.getInt(oldest.getColumnIndex("_id")); Location fix = locationFromJson( oldest.getString( oldest.getColumnIndex(GeoRss.POSITION_QUEUE_JSON))); int status = pushLocation(fix); if (status == 200) { rssdb.log("queue push #"+id+" OK"); rssdb.mark_as_pushed(id); } else { rssdb.log("queue push #"+id+" FAIL "+status); } } oldest.close(); rssdb.log("** Finished queue push. size = "+rssdb.countPositionQueueRemaining()); } } public int pushLocation(Location fix) { Log.i(appTag, "sending id: "+settings.getString(SETTING_OPENID,"")+ " fix: " +fix.getLatitude()+" long: "+fix.getLongitude()+ " alt: "+fix.getAltitude() + " time: " + Util.DateTimeIso8601(fix.getTime()) + " acc: "+fix.getAccuracy()); rssdb.log("pushing fix "+" time: " + Util.DateTimeIso8601(fix.getTime()) + "("+fix.getTime()+") acc: "+fix.getAccuracy()); if (settings.getBoolean(SETTING_BEEP_ON_FIX, false)) { play_fix_beep(); } //ArrayList <NameValuePair> params = new ArrayList <NameValuePair>(); ArrayList<Map.Entry<String, String>> params = new ArrayList<Map.Entry<String, String>>(); addPostParameters(params, fix); last_pushed_fix = fix; last_pushed_time = System.currentTimeMillis(); OAuthAccessor accessor = LocationStorageProviders.defaultAccessor(this); String[] token_and_secret = LocationStorageProviders.getDefaultAccessToken(this); params.add(new OAuth.Parameter("oauth_token", token_and_secret[0])); accessor.tokenSecret = token_and_secret[1]; try { OAuthMessage omessage; Log.d(appTag, "invoke("+accessor+", POST, "+ICECONDOR_WRITE_URL+", "+params); omessage = oclient.invoke(accessor, "POST", ICECONDOR_WRITE_URL, params); omessage.getHeader("Result"); last_fix_http_status = 200; return last_fix_http_status; } catch (OAuthException e) { rssdb.log("push OAuthException "+e); } catch (URISyntaxException e) { rssdb.log("push URISyntaxException "+e); } catch (UnknownHostException e) { rssdb.log("push UnknownHostException "+e); } catch (IOException e) { // includes host not found rssdb.log("push IOException "+e); } last_fix_http_status = 500; return last_fix_http_status; // something went wrong } private void addPostParameters(ArrayList<Map.Entry<String, String>> dict, Location fix) { dict.add(new Util.Parameter("location[latitude]", Double.toString(fix.getLatitude()))); dict.add(new Util.Parameter("location[longitude]", Double.toString(fix.getLongitude()))); dict.add(new Util.Parameter("location[altitude]", Double.toString(fix.getAltitude()))); dict.add(new Util.Parameter("client[version]", ""+ICECONDOR_VERSION)); if(fix.hasAccuracy()) { dict.add(new Util.Parameter("location[accuracy]", Double.toString(fix.getAccuracy()))); } if(fix.hasBearing()) { dict.add(new Util.Parameter("location[heading]", Double.toString(fix.getBearing()))); } if(fix.hasSpeed()) { dict.add(new Util.Parameter("location[velocity]", Double.toString(fix.getSpeed()))); } dict.add(new Util.Parameter("location[timestamp]", Util.DateTimeIso8601(fix.getTime()))); } public void onLocationChanged(Location location) { last_local_fix = location; long time_since_last_update = last_local_fix.getTime() - (last_recorded_fix == null?0:last_recorded_fix.getTime()); long record_frequency = Long.decode(settings.getString(SETTING_TRANSMISSION_FREQUENCY, "180000")); rssdb.log("pigeon onLocationChanged: lat:"+location.getLatitude()+ " long:"+location.getLongitude() + " acc:"+ location.getAccuracy()+" "+ (time_since_last_update/1000)+" seconds since last update"); if (on_switch) { if((last_local_fix.getAccuracy() < (last_recorded_fix == null? 500000:last_recorded_fix.getAccuracy())) || time_since_last_update > record_frequency ) { last_recorded_fix = last_local_fix; last_fix_http_status = 200; long id = rssdb.addPosition(locationToJson(last_local_fix)); rssdb.log("Pigeon location queued. location #"+id); pushQueue(); } } } private String locationToJson(Location lastLocalFix) { try { JSONObject position = new JSONObject(); position.put("latitude", lastLocalFix.getLatitude()); position.put("longitude", lastLocalFix.getLongitude()); position.put("time", lastLocalFix.getTime()); position.put("altitude", lastLocalFix.getAltitude()); position.put("accuracy", lastLocalFix.getAccuracy()); position.put("bearing", lastLocalFix.getBearing()); position.put("speed", lastLocalFix.getSpeed()); JSONObject jloc = new JSONObject(); jloc.put("location", position); return jloc.toString(); } catch (JSONException e) { return "{\"ERROR\":\""+e.toString()+"\"}"; } } private Location locationFromJson(String json) { try { JSONObject j = new JSONObject(json); JSONObject p = j.getJSONObject("location"); Location l = new Location(""); l.setLatitude(p.getDouble("latitude")); l.setLongitude(p.getDouble("longitude")); l.setTime(p.getLong("time")); l.setAltitude(p.getDouble("altitude")); l.setAccuracy(new Float(p.getDouble("accuracy"))); l.setBearing(new Float(p.getDouble("bearing"))); l.setSpeed(new Float(p.getDouble("speed"))); return l; } catch (JSONException e) { e.printStackTrace(); return null; } } private void play_fix_beep() { mp.start(); } public void onProviderDisabled(String provider) { Log.i(appTag, "provider "+provider+" disabled"); rssdb.log("provider "+provider+" disabled"); } public void onProviderEnabled(String provider) { Log.i(appTag, "provider "+provider+" enabled"); rssdb.log("provider "+provider+" enabled"); } public void onStatusChanged(String provider, int status, Bundle extras) { String status_msg = ""; if (status == LocationProvider.TEMPORARILY_UNAVAILABLE) {status_msg = "TEMPORARILY_UNAVAILABLE";} if (status == LocationProvider.OUT_OF_SERVICE) {status_msg = "OUT_OF_SERVICE";} if (status == LocationProvider.AVAILABLE) {status_msg = "AVAILABLE";} Log.i(appTag, "provider "+provider+" status changed to "+status_msg); rssdb.log("GPS "+status_msg); } @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String pref_name) { Log.i(appTag, "shared preference changed: "+pref_name); if (pref_name.equals(SETTING_TRANSMISSION_FREQUENCY)) { if (on_switch) { stopLocationUpdates(); startLocationUpdates(); notificationFlash("Position reporting frequency now "+Util.millisecondsToWords( Long.parseLong(prefs.getString(pref_name, "N/A")))); } } if (pref_name.equals(SETTING_RSS_READ_FREQUENCY)) { stopRssTimer(); startRssTimer(); notificationFlash("RSS Read frequency now "+Util.millisecondsToWords( Long.parseLong(prefs.getString(pref_name, "N/A")))); } } private void startHeartbeatTimer() { heartbeat_timer = new Timer("Heartbeat Timer"); heartbeatTask = new HeartBeatTask(); heartbeat_timer.scheduleAtFixedRate(heartbeatTask, 0, 20000); } private void startRssTimer() { rss_timer = new Timer("RSS Reader Timer"); long rss_read_frequency = Long.decode(settings.getString(SETTING_RSS_READ_FREQUENCY, "60000")); Log.i(appTag, "starting rss timer at frequency "+rss_read_frequency); rss_timer.scheduleAtFixedRate( new TimerTask() { public void run() { Log.i(appTag, "rss_timer fired"); updateRSS(); } }, 0, rss_read_frequency); } private void stopRssTimer() { rss_timer.cancel(); } private void startPushQueueTimer() { push_queue_timer = new Timer("PushQueue Timer"); push_queue_timer.scheduleAtFixedRate(new PushQueueTask(), 0, 30000); } private void stopPushQueueTimer() { push_queue_timer.cancel(); } protected void updateRSS() { new Timer().schedule( new TimerTask() { public void run() { Log.i(appTag, "rss_timer fired"); Cursor geoRssUrls = rssdb.findFeeds(); while (geoRssUrls.moveToNext()) { try { rssdb.readGeoRss(geoRssUrls); } catch (ClientProtocolException e) { Log.i(appTag, "http protocol exception "+e); } catch (IOException e) { Log.i(appTag, "io error "+e); } } geoRssUrls.close(); } }, 0); } class HeartBeatTask extends TimerTask { public void run() { String fix_part = ""; if (on_switch) { if (last_pushed_fix != null) { String ago = Util.timeAgoInWords(last_pushed_time); String fago = Util.timeAgoInWords(last_pushed_fix.getTime()); if (last_fix_http_status != 200) { ago = "err."; } fix_part = "push "+ ago+"/"+fago+"."; } if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { fix_part = "Warning: GPS set to disabled"; } } else { fix_part = "Location reporting is off."; } String queue_part = ""+rssdb.countPositionQueueRemaining()+" queued."; String beat_part = ""; if (last_local_fix != null) { String ago = Util.timeAgoInWords(last_local_fix.getTime()); beat_part = "fix "+ago+"."; } String msg = fix_part+" "+beat_part+" "+queue_part; notificationStatusUpdate(msg); } }; private final PigeonService.Stub pigeonBinder = new PigeonService.Stub() { public boolean isTransmitting() throws RemoteException { Log.i(appTag, "isTransmitting => "+on_switch); return on_switch; } public void startTransmitting() throws RemoteException { if (on_switch) { Log.i(appTag, "startTransmitting: already transmitting"); } else { Log.i(appTag, "startTransmitting"); on_switch = true; settings.edit().putBoolean(SETTING_PIGEON_TRANSMITTING, on_switch).commit(); startLocationUpdates(); notificationStatusUpdate("Waiting for fix."); notificationFlash("Location reporting ON."); } } public void stopTransmitting() throws RemoteException { Log.i(appTag, "stopTransmitting"); on_switch = false; settings.edit().putBoolean(SETTING_PIGEON_TRANSMITTING,on_switch).commit(); stopLocationUpdates(); notificationStatusUpdate("Location reporting is off."); notificationFlash("Location reporting OFF."); } public Location getLastFix() throws RemoteException { if(on_switch) { return last_local_fix; } else { return locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } } @Override public Location getLastPushedFix() throws RemoteException { return last_pushed_fix; } @Override public void refreshRSS() throws RemoteException { updateRSS(); } @Override public void pushFix() throws RemoteException { pushQueue(); } }; }
true
true
public void onCreate() { Log.i(appTag, "*** service created."); super.onCreate(); /* Database */ rssdb = new GeoRss(this); rssdb.open(); rssdb.log("Pigon created"); /* GPS */ locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); Log.i(appTag, "GPS provider enabled: "+locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)); last_local_fix = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); Log.i(appTag, "NETWORK provider enabled: "+locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)); Location last_network_fix = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); Log.i(appTag, "Last known NETWORK fix: "+last_network_fix+" "+Util.DateTimeIso8601(last_network_fix.getTime())); if (last_local_fix == null) { // fall back onto the network location last_local_fix = last_network_fix; } else { Log.i(appTag, "Last known GPS fix: "+last_local_fix+" "+Util.DateTimeIso8601(last_local_fix.getTime())); } /* WIFI */ wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); /* Notifications */ notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Start.class), 0); CharSequence text = getText(R.string.status_started); ongoing_notification = new Notification(R.drawable.condorhead_statusbar, text, System .currentTimeMillis()); ongoing_notification.flags = ongoing_notification.flags ^ Notification.FLAG_ONGOING_EVENT; ongoing_notification.setLatestEventInfo(this, "IceCondor", "", contentIntent); /* Preferences */ settings = PreferenceManager.getDefaultSharedPreferences(this); settings.registerOnSharedPreferenceChangeListener(this); on_switch = settings.getBoolean(SETTING_PIGEON_TRANSMITTING, false); if (on_switch) { //startForeground(1, ongoing_notification); startLocationUpdates(); } /* Sound */ mp = MediaPlayer.create(this, R.raw.beep); startHeartbeatTimer(); startRssTimer(); startPushQueueTimer(); /* Apache HTTP Monstrosity*/ httpClient = new DefaultHttpClient(); httpClient.getParams().setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 15 *1000); httpClient.getParams().setIntParameter(AllClientPNames.SO_TIMEOUT, 30 *1000); oclient = new OAuthClient(new HttpClient4()); }
public void onCreate() { Log.i(appTag, "*** service created."); super.onCreate(); /* Database */ rssdb = new GeoRss(this); rssdb.open(); rssdb.log("Pigon created"); /* GPS */ locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); Log.i(appTag, "GPS provider enabled: "+locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)); last_local_fix = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); Log.i(appTag, "NETWORK provider enabled: "+locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)); Location last_network_fix = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (last_local_fix == null) { if(last_network_fix != null) { last_local_fix = last_network_fix; // fall back onto the network location Log.i(appTag, "Last known NETWORK fix: "+last_network_fix+" "+Util.DateTimeIso8601(last_network_fix.getTime())); } } else { Log.i(appTag, "Last known GPS fix: "+last_local_fix+" "+Util.DateTimeIso8601(last_local_fix.getTime())); } /* WIFI */ wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); /* Notifications */ notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Start.class), 0); CharSequence text = getText(R.string.status_started); ongoing_notification = new Notification(R.drawable.condorhead_statusbar, text, System .currentTimeMillis()); ongoing_notification.flags = ongoing_notification.flags ^ Notification.FLAG_ONGOING_EVENT; ongoing_notification.setLatestEventInfo(this, "IceCondor", "", contentIntent); /* Preferences */ settings = PreferenceManager.getDefaultSharedPreferences(this); settings.registerOnSharedPreferenceChangeListener(this); on_switch = settings.getBoolean(SETTING_PIGEON_TRANSMITTING, false); if (on_switch) { //startForeground(1, ongoing_notification); startLocationUpdates(); } /* Sound */ mp = MediaPlayer.create(this, R.raw.beep); startHeartbeatTimer(); startRssTimer(); startPushQueueTimer(); /* Apache HTTP Monstrosity*/ httpClient = new DefaultHttpClient(); httpClient.getParams().setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 15 *1000); httpClient.getParams().setIntParameter(AllClientPNames.SO_TIMEOUT, 30 *1000); oclient = new OAuthClient(new HttpClient4()); }
diff --git a/src/TreeAutomata/FiniteTreesTable.java b/src/TreeAutomata/FiniteTreesTable.java index 07b76ef..7c4480a 100644 --- a/src/TreeAutomata/FiniteTreesTable.java +++ b/src/TreeAutomata/FiniteTreesTable.java @@ -1,88 +1,88 @@ package TreeAutomata; import java.util.*; import java.util.Map.Entry; public class FiniteTreesTable { public HashMap<Integer, HashSet<HashSet<Integer>>> FiniteTreesTable; public FiniteTreesTable(HashSet<Transition> tr, HashSet<Integer> ac) { FiniteTreesTable = new HashMap<Integer, HashSet<HashSet<Integer>>>(); HashSet<Transition> transRelWorkCopy = (HashSet<Transition>) tr.clone(); HashSet<Transition> transToEliminate = new HashSet<Transition>(); boolean transitionAdded; do { transitionAdded = false; transRelWorkCopy.removeAll(transToEliminate); transToEliminate.clear(); for (Transition trans : transRelWorkCopy) { HashSet<HashSet<Integer>> tmpSetOfStates; if ((ac.contains(trans.rightChildren) && ac.contains(trans.leftChildren)) - || FiniteTreesTable.containsKey(trans.leftChildren) && ac.contains(trans.rightChildren) - || FiniteTreesTable.containsKey(trans.rightChildren)&& ac.contains(trans.leftChildren) - || FiniteTreesTable.containsKey(trans.leftChildren) && FiniteTreesTable.containsKey(trans.rightChildren)) { + || FiniteTreesTable.containsKey(trans.leftChildren) && (!trans.node.equals(trans.leftChildren) || ac.contains(trans.node)) && ac.contains(trans.rightChildren) + || FiniteTreesTable.containsKey(trans.rightChildren) && (!trans.node.equals(trans.rightChildren) || ac.contains(trans.node)) && ac.contains(trans.leftChildren) + || FiniteTreesTable.containsKey(trans.leftChildren) && (!trans.node.equals(trans.leftChildren) || ac.contains(trans.node)) && FiniteTreesTable.containsKey(trans.rightChildren) && (!trans.node.equals(trans.rightChildren) || ac.contains(trans.node))) { HashSet<Integer> tmpStates = new HashSet<Integer>(); tmpStates.add(trans.rightChildren); tmpStates.add(trans.leftChildren); if (FiniteTreesTable.containsKey(trans.node)) { tmpSetOfStates = FiniteTreesTable.get(trans.node); } else { tmpSetOfStates = new HashSet<HashSet<Integer>>(); } tmpSetOfStates.add(tmpStates); transToEliminate.add(trans); FiniteTreesTable.put(trans.node, tmpSetOfStates); transitionAdded = true; } } } while (transitionAdded); } public boolean containsBadStates() { for (Entry<Integer, HashSet<HashSet<Integer>>> entryOfTable : FiniteTreesTable.entrySet()) { for (HashSet<Integer> tree : entryOfTable.getValue()) { if (!FiniteTreesTable.keySet().containsAll(tree)) return true; } } return false; } public boolean hasEmptyTreesSet(Integer state) { return !FiniteTreesTable.containsKey(state); } public HashSet<Integer> getStates() { return new HashSet(FiniteTreesTable.keySet()); } public void removeIncoerentTrees() { HashSet<HashSet<Integer>> treeToRemove = new HashSet<HashSet<Integer>>(); HashSet<Integer> keyToRemove = new HashSet<Integer>(); Set<Integer> goodStates = FiniteTreesTable.keySet(); for (Entry<Integer, HashSet<HashSet<Integer>>> entryOfTable : FiniteTreesTable.entrySet()) { for (HashSet<Integer> tree : entryOfTable.getValue()) { if (!goodStates.containsAll(tree)) { treeToRemove.add(tree); } } for(HashSet<Integer> tree : treeToRemove){ entryOfTable.getValue().remove(tree); } treeToRemove.clear(); if (entryOfTable.getValue().isEmpty()) { keyToRemove.add(entryOfTable.getKey()); } } for (Integer key : keyToRemove) FiniteTreesTable.remove(key); keyToRemove.clear(); } }
true
true
public FiniteTreesTable(HashSet<Transition> tr, HashSet<Integer> ac) { FiniteTreesTable = new HashMap<Integer, HashSet<HashSet<Integer>>>(); HashSet<Transition> transRelWorkCopy = (HashSet<Transition>) tr.clone(); HashSet<Transition> transToEliminate = new HashSet<Transition>(); boolean transitionAdded; do { transitionAdded = false; transRelWorkCopy.removeAll(transToEliminate); transToEliminate.clear(); for (Transition trans : transRelWorkCopy) { HashSet<HashSet<Integer>> tmpSetOfStates; if ((ac.contains(trans.rightChildren) && ac.contains(trans.leftChildren)) || FiniteTreesTable.containsKey(trans.leftChildren) && ac.contains(trans.rightChildren) || FiniteTreesTable.containsKey(trans.rightChildren)&& ac.contains(trans.leftChildren) || FiniteTreesTable.containsKey(trans.leftChildren) && FiniteTreesTable.containsKey(trans.rightChildren)) { HashSet<Integer> tmpStates = new HashSet<Integer>(); tmpStates.add(trans.rightChildren); tmpStates.add(trans.leftChildren); if (FiniteTreesTable.containsKey(trans.node)) { tmpSetOfStates = FiniteTreesTable.get(trans.node); } else { tmpSetOfStates = new HashSet<HashSet<Integer>>(); } tmpSetOfStates.add(tmpStates); transToEliminate.add(trans); FiniteTreesTable.put(trans.node, tmpSetOfStates); transitionAdded = true; } } } while (transitionAdded); }
public FiniteTreesTable(HashSet<Transition> tr, HashSet<Integer> ac) { FiniteTreesTable = new HashMap<Integer, HashSet<HashSet<Integer>>>(); HashSet<Transition> transRelWorkCopy = (HashSet<Transition>) tr.clone(); HashSet<Transition> transToEliminate = new HashSet<Transition>(); boolean transitionAdded; do { transitionAdded = false; transRelWorkCopy.removeAll(transToEliminate); transToEliminate.clear(); for (Transition trans : transRelWorkCopy) { HashSet<HashSet<Integer>> tmpSetOfStates; if ((ac.contains(trans.rightChildren) && ac.contains(trans.leftChildren)) || FiniteTreesTable.containsKey(trans.leftChildren) && (!trans.node.equals(trans.leftChildren) || ac.contains(trans.node)) && ac.contains(trans.rightChildren) || FiniteTreesTable.containsKey(trans.rightChildren) && (!trans.node.equals(trans.rightChildren) || ac.contains(trans.node)) && ac.contains(trans.leftChildren) || FiniteTreesTable.containsKey(trans.leftChildren) && (!trans.node.equals(trans.leftChildren) || ac.contains(trans.node)) && FiniteTreesTable.containsKey(trans.rightChildren) && (!trans.node.equals(trans.rightChildren) || ac.contains(trans.node))) { HashSet<Integer> tmpStates = new HashSet<Integer>(); tmpStates.add(trans.rightChildren); tmpStates.add(trans.leftChildren); if (FiniteTreesTable.containsKey(trans.node)) { tmpSetOfStates = FiniteTreesTable.get(trans.node); } else { tmpSetOfStates = new HashSet<HashSet<Integer>>(); } tmpSetOfStates.add(tmpStates); transToEliminate.add(trans); FiniteTreesTable.put(trans.node, tmpSetOfStates); transitionAdded = true; } } } while (transitionAdded); }
diff --git a/bonaparte-i18n/src/main/java/de/jpaw/bonaparte/core/ICUCSVConfiguration.java b/bonaparte-i18n/src/main/java/de/jpaw/bonaparte/core/ICUCSVConfiguration.java index ee70ee3b..1b61e934 100644 --- a/bonaparte-i18n/src/main/java/de/jpaw/bonaparte/core/ICUCSVConfiguration.java +++ b/bonaparte-i18n/src/main/java/de/jpaw/bonaparte/core/ICUCSVConfiguration.java @@ -1,68 +1,68 @@ package de.jpaw.bonaparte.core; import java.util.Locale; import com.ibm.icu.util.ULocale; import de.jpaw.bonaparte.core.CSVConfiguration.Builder; public class ICUCSVConfiguration extends CSVConfiguration { public final ULocale ulocale; // the ICU locale replacement (597 instead of 159 available Locales) public ICUCSVConfiguration(String separator, Character quote, String quoteReplacement, String ctrlReplacement, boolean datesQuoted, boolean removePoint4BD, String mapStart, String mapEnd, String arrayStart, String arrayEnd, String objectStart, String objectEnd, String booleanTrue, String booleanFalse, Locale locale, CSVStyle dateStyle, CSVStyle timeStyle, String customDayFormat, String customTimestampFormat, String customTimestampWithMsFormat, String customCalendarFormat, ULocale ulocale) { super(separator, quote, quoteReplacement, ctrlReplacement, datesQuoted, removePoint4BD, mapStart, mapEnd, arrayStart, arrayEnd, objectStart, objectEnd, booleanTrue, booleanFalse, locale, dateStyle, timeStyle, customDayFormat, customTimestampFormat, customTimestampWithMsFormat, - customCalendarFormat); + customCalendarFormat, false); this.ulocale = ulocale; } /** Creates a new CSVConfiguration.Builder based on the current object. */ public Builder builder() { return new Builder(this); } /** Builder for the configuration */ public static class Builder extends CSVConfiguration.Builder { private ULocale ulocale; // used to determine date format protected final void xferBaseClass(ICUCSVConfiguration cfg) { super.xferBaseClass(cfg); this.ulocale = cfg.ulocale; } /** Creates a new CSVConfiguration.Builder with default settings. */ public Builder() { xferBaseClass(CSV_DEFAULT_CONFIGURATION); this.ulocale = ULocale.US; } /** Creates a new CSVConfiguration.Builder from some existing configuration. */ public Builder(ICUCSVConfiguration cfg) { xferBaseClass(cfg); } /** Creates a new CSVConfiguration.Builder (as a factory method). */ public static Builder from(ICUCSVConfiguration cfg) { return new Builder(cfg); } /** Constructs the CSVConfiguration from the data collected so far */ public ICUCSVConfiguration build() { return new ICUCSVConfiguration(separator, quote, quoteReplacement, ctrlReplacement, datesQuoted, removePoint4BD, mapStart, mapEnd, arrayStart, arrayEnd, objectStart, objectEnd, booleanTrue, booleanFalse, locale, dateStyle, timeStyle, customDayFormat, customTimestampFormat, customTimestampWithMsFormat, customCalendarFormat, ulocale); } // now the individual builder setters follow public Builder forULocale(ULocale ulocale) { this.ulocale = ulocale; return this; } } }
true
true
public ICUCSVConfiguration(String separator, Character quote, String quoteReplacement, String ctrlReplacement, boolean datesQuoted, boolean removePoint4BD, String mapStart, String mapEnd, String arrayStart, String arrayEnd, String objectStart, String objectEnd, String booleanTrue, String booleanFalse, Locale locale, CSVStyle dateStyle, CSVStyle timeStyle, String customDayFormat, String customTimestampFormat, String customTimestampWithMsFormat, String customCalendarFormat, ULocale ulocale) { super(separator, quote, quoteReplacement, ctrlReplacement, datesQuoted, removePoint4BD, mapStart, mapEnd, arrayStart, arrayEnd, objectStart, objectEnd, booleanTrue, booleanFalse, locale, dateStyle, timeStyle, customDayFormat, customTimestampFormat, customTimestampWithMsFormat, customCalendarFormat); this.ulocale = ulocale; }
public ICUCSVConfiguration(String separator, Character quote, String quoteReplacement, String ctrlReplacement, boolean datesQuoted, boolean removePoint4BD, String mapStart, String mapEnd, String arrayStart, String arrayEnd, String objectStart, String objectEnd, String booleanTrue, String booleanFalse, Locale locale, CSVStyle dateStyle, CSVStyle timeStyle, String customDayFormat, String customTimestampFormat, String customTimestampWithMsFormat, String customCalendarFormat, ULocale ulocale) { super(separator, quote, quoteReplacement, ctrlReplacement, datesQuoted, removePoint4BD, mapStart, mapEnd, arrayStart, arrayEnd, objectStart, objectEnd, booleanTrue, booleanFalse, locale, dateStyle, timeStyle, customDayFormat, customTimestampFormat, customTimestampWithMsFormat, customCalendarFormat, false); this.ulocale = ulocale; }
diff --git a/src/com/android/gallery3d/app/AbstractGalleryActivity.java b/src/com/android/gallery3d/app/AbstractGalleryActivity.java index 144485df8..7e9f50a04 100644 --- a/src/com/android/gallery3d/app/AbstractGalleryActivity.java +++ b/src/com/android/gallery3d/app/AbstractGalleryActivity.java @@ -1,269 +1,269 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.gallery3d.app; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Configuration; import android.os.Bundle; import android.view.MenuItem; import android.view.Window; import android.view.WindowManager; import com.android.gallery3d.R; import com.android.gallery3d.data.DataManager; import com.android.gallery3d.data.MediaItem; import com.android.gallery3d.ui.GLRoot; import com.android.gallery3d.ui.GLRootView; import com.android.gallery3d.util.ThreadPool; public class AbstractGalleryActivity extends Activity implements GalleryActivity { @SuppressWarnings("unused") private static final String TAG = "AbstractGalleryActivity"; private GLRootView mGLRootView; private StateManager mStateManager; private GalleryActionBar mActionBar; private OrientationManager mOrientationManager; private TransitionStore mTransitionStore = new TransitionStore(); private boolean mDisableToggleStatusBar; private AlertDialog mAlertDialog = null; private BroadcastReceiver mMountReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (getExternalCacheDir() != null) onStorageReady(); } }; private IntentFilter mMountFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mOrientationManager = new OrientationManager(this); toggleStatusBarByOrientation(); getWindow().setBackgroundDrawable(null); } @Override protected void onSaveInstanceState(Bundle outState) { mGLRootView.lockRenderThread(); try { super.onSaveInstanceState(outState); getStateManager().saveState(outState); } finally { mGLRootView.unlockRenderThread(); } } @Override public void onConfigurationChanged(Configuration config) { super.onConfigurationChanged(config); mStateManager.onConfigurationChange(config); invalidateOptionsMenu(); toggleStatusBarByOrientation(); } public Context getAndroidContext() { return this; } public DataManager getDataManager() { return ((GalleryApp) getApplication()).getDataManager(); } public ThreadPool getThreadPool() { return ((GalleryApp) getApplication()).getThreadPool(); } public synchronized StateManager getStateManager() { if (mStateManager == null) { mStateManager = new StateManager(this); } return mStateManager; } public GLRoot getGLRoot() { return mGLRootView; } public OrientationManager getOrientationManager() { return mOrientationManager; } @Override public void setContentView(int resId) { super.setContentView(resId); mGLRootView = (GLRootView) findViewById(R.id.gl_root_view); } protected void onStorageReady() { if (mAlertDialog != null) { mAlertDialog.dismiss(); mAlertDialog = null; unregisterReceiver(mMountReceiver); } } @Override protected void onStart() { super.onStart(); if (getExternalCacheDir() == null) { OnCancelListener onCancel = new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }; OnClickListener onClick = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }; mAlertDialog = new AlertDialog.Builder(this) .setIconAttribute(android.R.attr.alertDialogIcon) - .setTitle("No Storage") - .setMessage("No external storage available.") + .setTitle(R.string.no_storage_title) + .setMessage(R.string.no_storage_message) .setNegativeButton(android.R.string.cancel, onClick) .setOnCancelListener(onCancel) .show(); registerReceiver(mMountReceiver, mMountFilter); } } @Override protected void onStop() { super.onStop(); if (mAlertDialog != null) { unregisterReceiver(mMountReceiver); mAlertDialog.dismiss(); mAlertDialog = null; } } @Override protected void onResume() { super.onResume(); mGLRootView.lockRenderThread(); try { getStateManager().resume(); getDataManager().resume(); } finally { mGLRootView.unlockRenderThread(); } mGLRootView.onResume(); mOrientationManager.resume(); } @Override protected void onPause() { super.onPause(); mOrientationManager.pause(); mGLRootView.onPause(); mGLRootView.lockRenderThread(); try { getStateManager().pause(); getDataManager().pause(); } finally { mGLRootView.unlockRenderThread(); } MediaItem.getMicroThumbPool().clear(); MediaItem.getThumbPool().clear(); MediaItem.getBytesBufferPool().clear(); } @Override protected void onDestroy() { super.onDestroy(); mGLRootView.lockRenderThread(); try { getStateManager().destroy(); } finally { mGLRootView.unlockRenderThread(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { mGLRootView.lockRenderThread(); try { getStateManager().notifyActivityResult( requestCode, resultCode, data); } finally { mGLRootView.unlockRenderThread(); } } @Override public void onBackPressed() { // send the back event to the top sub-state GLRoot root = getGLRoot(); root.lockRenderThread(); try { getStateManager().onBackPressed(); } finally { root.unlockRenderThread(); } } @Override public GalleryActionBar getGalleryActionBar() { if (mActionBar == null) { mActionBar = new GalleryActionBar(this); } return mActionBar; } @Override public boolean onOptionsItemSelected(MenuItem item) { GLRoot root = getGLRoot(); root.lockRenderThread(); try { return getStateManager().itemSelected(item); } finally { root.unlockRenderThread(); } } protected void disableToggleStatusBar() { mDisableToggleStatusBar = true; } // Shows status bar in portrait view, hide in landscape view private void toggleStatusBarByOrientation() { if (mDisableToggleStatusBar) return; Window win = getWindow(); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } } @Override public TransitionStore getTransitionStore() { return mTransitionStore; } }
true
true
protected void onStart() { super.onStart(); if (getExternalCacheDir() == null) { OnCancelListener onCancel = new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }; OnClickListener onClick = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }; mAlertDialog = new AlertDialog.Builder(this) .setIconAttribute(android.R.attr.alertDialogIcon) .setTitle("No Storage") .setMessage("No external storage available.") .setNegativeButton(android.R.string.cancel, onClick) .setOnCancelListener(onCancel) .show(); registerReceiver(mMountReceiver, mMountFilter); } }
protected void onStart() { super.onStart(); if (getExternalCacheDir() == null) { OnCancelListener onCancel = new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }; OnClickListener onClick = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }; mAlertDialog = new AlertDialog.Builder(this) .setIconAttribute(android.R.attr.alertDialogIcon) .setTitle(R.string.no_storage_title) .setMessage(R.string.no_storage_message) .setNegativeButton(android.R.string.cancel, onClick) .setOnCancelListener(onCancel) .show(); registerReceiver(mMountReceiver, mMountFilter); } }
diff --git a/src/net/madmanmarkau/Give/Give.java b/src/net/madmanmarkau/Give/Give.java index d80473f..6c5b29f 100644 --- a/src/net/madmanmarkau/Give/Give.java +++ b/src/net/madmanmarkau/Give/Give.java @@ -1,194 +1,196 @@ package net.madmanmarkau.Give; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.util.config.Configuration; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import com.nijiko.permissions.PermissionHandler; import com.nijikokun.bukkit.Permissions.Permissions; // Permissions: // if (iStick.Permissions.has(player, "foo.bar")) {} public class Give extends JavaPlugin { public final Logger log = Logger.getLogger("Minecraft"); public PermissionHandler Permissions; public Configuration Config; public PluginDescriptionFile pdfFile; @Override public void onDisable() { log.info(pdfFile.getName() + " version " + pdfFile.getVersion() + " unloaded"); } @Override public void onEnable() { this.pdfFile = this.getDescription(); setupPermissions(); log.info(pdfFile.getName() + " version " + pdfFile.getVersion() + " loaded"); } public void setupPermissions() { Plugin perm = this.getServer().getPluginManager().getPlugin("Permissions"); if (this.Permissions == null) { if (perm!= null) { this.getServer().getPluginManager().enablePlugin(perm); this.Permissions = ((Permissions) perm).getHandler(); } else { log.info(pdfFile.getName() + " version " + pdfFile.getVersion() + "not enabled. Permissions not detected"); this.getServer().getPluginManager().disablePlugin(this); } } } public static Material getMaterial(String m) throws IllegalArgumentException { try { int itemId = Integer.decode(m); Material material = Material.getMaterial(itemId); if (material == null) { throw new IllegalArgumentException("Unknown material " + m); } return material; } catch (NumberFormatException ex) { Material material = Material.getMaterial(m.toUpperCase()); if (material == null) { throw new IllegalArgumentException("Unknown material " + m); } return material; } } @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Material material = null; int quantity = 1; Player player = null; if ( cmd.getName().compareToIgnoreCase("give") == 0 ) { if (sender instanceof Player) { // Player-sent command player = (Player) sender; if (Permissions.has(player, "give")) { if (args.length == 0) { - sender.sendMessage(ChatColor.RED + "&c/give <item> [<amount>]:"); + sender.sendMessage(ChatColor.RED + "/give <item> [<amount>]"); + return true; } if (args.length >= 1) { try { material = getMaterial(args[0]); } catch (IllegalArgumentException ex) { sender.sendMessage(ex.getMessage()); return true; } if (material == null) { sender.sendMessage("Unknown material " + args[0]); return true; } if (material.getId() == -1 || material.getId() == 0) { sender.sendMessage("Unknown or invalid material " + args[0]); return true; } } if (args.length >= 2) { try { quantity = Integer.decode(args[1]); } catch (NumberFormatException ex) { sender.sendMessage("Illegal quantity!"); return true; } } } else { return false; } } else { // Server/plugin sent command if (args.length == 0) { - sender.sendMessage(ChatColor.RED + "&c/give <player> <item> [<amount>]:"); + sender.sendMessage(ChatColor.RED + "/give <player> <item> [<amount>]"); + return true; } if (args.length >= 1) { try { player = sender.getServer().getPlayer(args[0]); } catch (IllegalArgumentException ex) { sender.sendMessage(ex.getMessage()); return true; } if (player == null) { sender.sendMessage("Unknown player " + args[0]); return true; } } if (args.length >= 2) { try { material = getMaterial(args[1]); } catch (IllegalArgumentException ex) { sender.sendMessage(ex.getMessage()); return true; } if (material == null) { sender.sendMessage("Unknown material " + args[1]); return true; } if (material.getId() == -1 || material.getId() == 0) { sender.sendMessage("Unknown or invalid material " + args[1]); return true; } } if (args.length >= 3) { try { quantity = Integer.decode(args[2]); } catch (NumberFormatException ex) { sender.sendMessage("Illegal quantity!"); return true; } } } // Valid options if (Permissions.has(player, "give." + material.getId()) || (sender != player)) { PlayerInventory inventory = player.getInventory(); inventory.addItem(new ItemStack[] { new ItemStack(material, quantity) }); if (sender == player) { sender.sendMessage("Here, have some " + material.toString()); } else { player.sendMessage("You have been given some " + material.toString()); } } else { sender.sendMessage("You may not have that item!"); } return true; } return false; } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Material material = null; int quantity = 1; Player player = null; if ( cmd.getName().compareToIgnoreCase("give") == 0 ) { if (sender instanceof Player) { // Player-sent command player = (Player) sender; if (Permissions.has(player, "give")) { if (args.length == 0) { sender.sendMessage(ChatColor.RED + "&c/give <item> [<amount>]:"); } if (args.length >= 1) { try { material = getMaterial(args[0]); } catch (IllegalArgumentException ex) { sender.sendMessage(ex.getMessage()); return true; } if (material == null) { sender.sendMessage("Unknown material " + args[0]); return true; } if (material.getId() == -1 || material.getId() == 0) { sender.sendMessage("Unknown or invalid material " + args[0]); return true; } } if (args.length >= 2) { try { quantity = Integer.decode(args[1]); } catch (NumberFormatException ex) { sender.sendMessage("Illegal quantity!"); return true; } } } else { return false; } } else { // Server/plugin sent command if (args.length == 0) { sender.sendMessage(ChatColor.RED + "&c/give <player> <item> [<amount>]:"); } if (args.length >= 1) { try { player = sender.getServer().getPlayer(args[0]); } catch (IllegalArgumentException ex) { sender.sendMessage(ex.getMessage()); return true; } if (player == null) { sender.sendMessage("Unknown player " + args[0]); return true; } } if (args.length >= 2) { try { material = getMaterial(args[1]); } catch (IllegalArgumentException ex) { sender.sendMessage(ex.getMessage()); return true; } if (material == null) { sender.sendMessage("Unknown material " + args[1]); return true; } if (material.getId() == -1 || material.getId() == 0) { sender.sendMessage("Unknown or invalid material " + args[1]); return true; } } if (args.length >= 3) { try { quantity = Integer.decode(args[2]); } catch (NumberFormatException ex) { sender.sendMessage("Illegal quantity!"); return true; } } } // Valid options if (Permissions.has(player, "give." + material.getId()) || (sender != player)) { PlayerInventory inventory = player.getInventory(); inventory.addItem(new ItemStack[] { new ItemStack(material, quantity) }); if (sender == player) { sender.sendMessage("Here, have some " + material.toString()); } else { player.sendMessage("You have been given some " + material.toString()); } } else { sender.sendMessage("You may not have that item!"); } return true; } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Material material = null; int quantity = 1; Player player = null; if ( cmd.getName().compareToIgnoreCase("give") == 0 ) { if (sender instanceof Player) { // Player-sent command player = (Player) sender; if (Permissions.has(player, "give")) { if (args.length == 0) { sender.sendMessage(ChatColor.RED + "/give <item> [<amount>]"); return true; } if (args.length >= 1) { try { material = getMaterial(args[0]); } catch (IllegalArgumentException ex) { sender.sendMessage(ex.getMessage()); return true; } if (material == null) { sender.sendMessage("Unknown material " + args[0]); return true; } if (material.getId() == -1 || material.getId() == 0) { sender.sendMessage("Unknown or invalid material " + args[0]); return true; } } if (args.length >= 2) { try { quantity = Integer.decode(args[1]); } catch (NumberFormatException ex) { sender.sendMessage("Illegal quantity!"); return true; } } } else { return false; } } else { // Server/plugin sent command if (args.length == 0) { sender.sendMessage(ChatColor.RED + "/give <player> <item> [<amount>]"); return true; } if (args.length >= 1) { try { player = sender.getServer().getPlayer(args[0]); } catch (IllegalArgumentException ex) { sender.sendMessage(ex.getMessage()); return true; } if (player == null) { sender.sendMessage("Unknown player " + args[0]); return true; } } if (args.length >= 2) { try { material = getMaterial(args[1]); } catch (IllegalArgumentException ex) { sender.sendMessage(ex.getMessage()); return true; } if (material == null) { sender.sendMessage("Unknown material " + args[1]); return true; } if (material.getId() == -1 || material.getId() == 0) { sender.sendMessage("Unknown or invalid material " + args[1]); return true; } } if (args.length >= 3) { try { quantity = Integer.decode(args[2]); } catch (NumberFormatException ex) { sender.sendMessage("Illegal quantity!"); return true; } } } // Valid options if (Permissions.has(player, "give." + material.getId()) || (sender != player)) { PlayerInventory inventory = player.getInventory(); inventory.addItem(new ItemStack[] { new ItemStack(material, quantity) }); if (sender == player) { sender.sendMessage("Here, have some " + material.toString()); } else { player.sendMessage("You have been given some " + material.toString()); } } else { sender.sendMessage("You may not have that item!"); } return true; } return false; }
diff --git a/midp20/Hecl.java b/midp20/Hecl.java index ab407615..679dc499 100644 --- a/midp20/Hecl.java +++ b/midp20/Hecl.java @@ -1,147 +1,147 @@ /* * Copyright (C) 2005-2008 data2c GmbH (www.data2c.com) * * Author: Wolfgang S. Kechel - [email protected] */ import java.io.IOException; import java.util.Vector; import javax.microedition.midlet.MIDlet; import javax.microedition.lcdui.Alert; import javax.microedition.lcdui.AlertType; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Gauge; import org.hecl.Interp; import org.hecl.HeclException; import org.hecl.HeclTask; import org.hecl.ListThing; import org.hecl.ObjectThing; import org.hecl.Thing; import org.hecl.midp20.MidletCmd; import org.hecl.misc.HeclUtils; import org.hecl.net.HttpCmd; import org.hecl.net.Base64Cmd; import org.hecl.rms.RMSCmd; /** * <code>Hecl</code> is the main class for the MIDP2.0 Hecl.jar. Use * this as an example if you want to create your own custom * application. * * @version 1.0 */ public class Hecl extends MIDlet { protected Interp interp = null; protected HeclTask evaltask = null; protected String[] args = {}; protected boolean started = false; public void destroyApp(boolean b) { notifyDestroyed(); } public void pauseApp() { if (interp.commandExists("midlet.onpause")) { interp.evalAsync(new Thing("midlet.onpause")); } } public void startApp() { if (started) { if (interp.commandExists("midlet.onresume")) { interp.evalAsync(new Thing("midlet.onresume")); } return; } started = true; Display display = Display.getDisplay(this); try { Alert a = new Alert("Loading Hecl", "Loading Hecl...", null, AlertType.INFO); display.setCurrent(a); a.setTimeout(Alert.FOREVER); a.setIndicator(new Gauge(null, false, Gauge.INDEFINITE, Gauge.CONTINUOUS_RUNNING)); interp = new Interp(); Vector v = new Vector(); for(int i = 0; i<args.length; ++i) { v.addElement(new Thing(args[i])); } interp.setVar("argv", ListThing.create(v)); // load extensions into interpreter... RMSCmd.load(interp); HttpCmd.load(interp); Base64Cmd.load(interp); //#if locationapi == 1 - LocationCmd.load(interp); + org.hecl.location.LocationCmd.load(interp); //#endif //#if kxml == 1 org.hecl.kxml.KXMLCmd.load(interp); //#endif //#if files == 1 org.hecl.files.FileCmds.load(interp); //#endif MidletCmd.load(interp,this); //#if mwt == 1 org.hecl.mwtgui.MwtCmds.load(interp, this); //#endif String scriptcontent = HeclUtils.getResourceAsString(this.getClass(),"/script.hcl","UTF-8"); interp.setVar("splash", ObjectThing.create(a)); evaltask = interp.evalIdle(new Thing(scriptcontent)); } catch (Exception e) { e.printStackTrace(); destroyApp(true); } } /** * The <code>runScript</code> method exists so that external * applications (emulators, primarily) can call into Hecl and run * scripts. * * @param s a <code>String</code> value */ public void runScript(String s) { try { /* First wait for the idleEval call to complete... */ while(evaltask == null) { Thread.currentThread().yield(); } while (!evaltask.isDone()) { try { synchronized(evaltask) { evaltask.wait(); } } catch(Exception e) { // ignore e.printStackTrace(); } } interp.eval(new Thing(s)); } catch (Exception e) { /* At least let the user know there was an error. */ Alert a = new Alert("Hecl error", e.toString(), null, null); Display display = Display.getDisplay(this); display.setCurrent(a); /* e.printStackTrace(); */ System.err.println("Error in runScript: " + e); } } }
true
true
public void startApp() { if (started) { if (interp.commandExists("midlet.onresume")) { interp.evalAsync(new Thing("midlet.onresume")); } return; } started = true; Display display = Display.getDisplay(this); try { Alert a = new Alert("Loading Hecl", "Loading Hecl...", null, AlertType.INFO); display.setCurrent(a); a.setTimeout(Alert.FOREVER); a.setIndicator(new Gauge(null, false, Gauge.INDEFINITE, Gauge.CONTINUOUS_RUNNING)); interp = new Interp(); Vector v = new Vector(); for(int i = 0; i<args.length; ++i) { v.addElement(new Thing(args[i])); } interp.setVar("argv", ListThing.create(v)); // load extensions into interpreter... RMSCmd.load(interp); HttpCmd.load(interp); Base64Cmd.load(interp); //#if locationapi == 1 LocationCmd.load(interp); //#endif //#if kxml == 1 org.hecl.kxml.KXMLCmd.load(interp); //#endif //#if files == 1 org.hecl.files.FileCmds.load(interp); //#endif MidletCmd.load(interp,this); //#if mwt == 1 org.hecl.mwtgui.MwtCmds.load(interp, this); //#endif String scriptcontent = HeclUtils.getResourceAsString(this.getClass(),"/script.hcl","UTF-8"); interp.setVar("splash", ObjectThing.create(a)); evaltask = interp.evalIdle(new Thing(scriptcontent)); } catch (Exception e) { e.printStackTrace(); destroyApp(true); } }
public void startApp() { if (started) { if (interp.commandExists("midlet.onresume")) { interp.evalAsync(new Thing("midlet.onresume")); } return; } started = true; Display display = Display.getDisplay(this); try { Alert a = new Alert("Loading Hecl", "Loading Hecl...", null, AlertType.INFO); display.setCurrent(a); a.setTimeout(Alert.FOREVER); a.setIndicator(new Gauge(null, false, Gauge.INDEFINITE, Gauge.CONTINUOUS_RUNNING)); interp = new Interp(); Vector v = new Vector(); for(int i = 0; i<args.length; ++i) { v.addElement(new Thing(args[i])); } interp.setVar("argv", ListThing.create(v)); // load extensions into interpreter... RMSCmd.load(interp); HttpCmd.load(interp); Base64Cmd.load(interp); //#if locationapi == 1 org.hecl.location.LocationCmd.load(interp); //#endif //#if kxml == 1 org.hecl.kxml.KXMLCmd.load(interp); //#endif //#if files == 1 org.hecl.files.FileCmds.load(interp); //#endif MidletCmd.load(interp,this); //#if mwt == 1 org.hecl.mwtgui.MwtCmds.load(interp, this); //#endif String scriptcontent = HeclUtils.getResourceAsString(this.getClass(),"/script.hcl","UTF-8"); interp.setVar("splash", ObjectThing.create(a)); evaltask = interp.evalIdle(new Thing(scriptcontent)); } catch (Exception e) { e.printStackTrace(); destroyApp(true); } }
diff --git a/software/caTissue/modules/caTissueStaticDataService/src/edu/wustl/catissuecore/domain/util/CollectionsHandler.java b/software/caTissue/modules/caTissueStaticDataService/src/edu/wustl/catissuecore/domain/util/CollectionsHandler.java index 7c30bbbf4..4b85a5fe9 100644 --- a/software/caTissue/modules/caTissueStaticDataService/src/edu/wustl/catissuecore/domain/util/CollectionsHandler.java +++ b/software/caTissue/modules/caTissueStaticDataService/src/edu/wustl/catissuecore/domain/util/CollectionsHandler.java @@ -1,164 +1,164 @@ package edu.wustl.catissuecore.domain.util; import org.apache.log4j.Logger; import org.springframework.util.ReflectionUtils; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.*; /** * @author Ion C. Olaru * Date: 1/18/12 * This class is resetting the collections that are throwing org.hibernate.LazyInitializationException due to a * caTissue side hibernate approach. Also, circle references are removed to make AXIS capable of successful marshaling. */ public class CollectionsHandler { private static Logger log = Logger.getLogger(PropertiesLoader.class); /** * Get all the field declared in a class including the ones declared in all superclasses. * @param c Class to get the fields from * @return The list of class fields */ private static List<Field> getFields(Class c) { List<Field> fields = new ArrayList<Field>(); Field[] localFields = c.getDeclaredFields(); if (localFields != null) { fields.addAll(Arrays.asList(localFields)); } if (c.getSuperclass() != null) { List superFields = getFields(c.getSuperclass()); if (superFields != null && superFields.size() > 0) { fields.addAll(superFields); } } return fields; } /** * Determines whether the given type is a collection * @param c Class type * @return true if "c" is a collection */ public static boolean isCollection(Class c) { if (c == java.util.Collection.class || c == java.util.Set.class || c == java.util.List.class) return true; Class[] is = c.getInterfaces(); for (Class _i : is) { if (_i == java.util.Collection.class || _i == java.util.Set.class || _i == java.util.List.class) return true; } return false; } /** * Determines whether the given type is a java.util.Set * @param c Class type * @return true if "c" is a collection */ public static boolean isSet(Class c) { return (c == java.util.Set.class); } public static boolean isJavaType(Class c) { if (c.isPrimitive()) return true; if (c.getPackage().getName().equals("java.lang")) return true; if (c.getPackage().getName().equals("java.util")) return true; return false; } /** * Does the processing described in the class header for a particular object * First it check the collections them moves to the other types which may have their own collections. * IT IS IMPORTANT TO PROCESS COLLECTIONS FIRST SINCE THEY ARE PART OF java.util PACKAGE WHICH IS * EXCLUDED IN THE else BRANCH * @param o Object to be processed * @param objectCache cache of object, to avoid circular references */ public static void handleObject(Object o, Set objectCache) { if (o == null) return; if (objectCache.contains(o)) { return; } objectCache.add(o); List<Field> fields = getFields(o.getClass()); for (Field f : fields) { if (isCollection(f.getType())) { Collection c = (Collection)doInvokeGetter(f, o, true); log.debug(">>> COLLECTION RECEIVED: " + f.getName()); handleCollection(c, objectCache); } else { if (!isJavaType(f.getType())) { log.debug(">>> NOW PROCESSING: " + f.getName() + " OF TYPE " + f.getType()); // Handle the other fields that may have their own Collections fields handleObject(doInvokeGetter(f, o, false), objectCache); } } } } /** * Invokes the getter, if it exists, of the given field for a particular class and suppress any thrown exceptions. * Fields for which getter throws an org.hibernate.LazyInitializationException are reset to an empty java.util.ArrayList * @param o Object which class which contains the field * @param f Field to invoke the setter for * @param invokeSize whether to invoke the method on the collection to handle Lazy Init * @return the object returned by the getter method */ public static Object doInvokeGetter(Field f, Object o, boolean invokeSize) { PropertyDescriptor pd = null; try { pd = new PropertyDescriptor(f.getName(), o.getClass()); Method readMethod = pd.getReadMethod(); log.debug(">>> GETTER: " + readMethod); Object getterResult = readMethod.invoke(o); // DO NOT REMOVE THE NEXT LINE, SINCE IT HAS TO BE CALLED IN ORDER TO TRIGGER THE LAZY EXCEPTION IF THE CASE getterResult.toString(); // log.debug(">>> getterResult: " + getterResult); - // IF o IS A LAZY COLLECTION WE TRIGGER THE EXCEPTION BY CALLING "getSize()" ON IT + // IF o IS A LAZY COLLECTION WE TRIGGER THE EXCEPTION BY CALLING "size()" ON IT if (invokeSize) { Method sizeMethod = getterResult.getClass().getMethod("size"); sizeMethod.invoke(getterResult); } return getterResult; } catch (Throwable e) { Method writeMethod = pd.getWriteMethod(); try { log.debug(">>> SETTER: " + writeMethod); if (isCollection(f.getType())) { if (isSet(f.getType())) writeMethod.invoke(o, new java.util.HashSet()); else writeMethod.invoke(o, new java.util.ArrayList()); } else { Class returnedType = pd.getReadMethod().getReturnType(); writeMethod.invoke(o, returnedType.newInstance()); } } catch (Exception e1) { throw new RuntimeException(String.format("Exception on invoking method '%s' on class '%s'.", f.getName(), o.getClass()), e1); } } return null; } /** * Does the processing described in the class header for a particular collection of objects * @param c Collection to be processed */ public static void handleCollection(Collection c, Set objectCache) { if (c == null || c.size() == 0) return; log.debug(">>> COLLECTION: " + c.getClass().getName()); for (Object o : c) { handleObject(o, objectCache); } } }
true
true
public static Object doInvokeGetter(Field f, Object o, boolean invokeSize) { PropertyDescriptor pd = null; try { pd = new PropertyDescriptor(f.getName(), o.getClass()); Method readMethod = pd.getReadMethod(); log.debug(">>> GETTER: " + readMethod); Object getterResult = readMethod.invoke(o); // DO NOT REMOVE THE NEXT LINE, SINCE IT HAS TO BE CALLED IN ORDER TO TRIGGER THE LAZY EXCEPTION IF THE CASE getterResult.toString(); // log.debug(">>> getterResult: " + getterResult); // IF o IS A LAZY COLLECTION WE TRIGGER THE EXCEPTION BY CALLING "getSize()" ON IT if (invokeSize) { Method sizeMethod = getterResult.getClass().getMethod("size"); sizeMethod.invoke(getterResult); } return getterResult; } catch (Throwable e) { Method writeMethod = pd.getWriteMethod(); try { log.debug(">>> SETTER: " + writeMethod); if (isCollection(f.getType())) { if (isSet(f.getType())) writeMethod.invoke(o, new java.util.HashSet()); else writeMethod.invoke(o, new java.util.ArrayList()); } else { Class returnedType = pd.getReadMethod().getReturnType(); writeMethod.invoke(o, returnedType.newInstance()); } } catch (Exception e1) { throw new RuntimeException(String.format("Exception on invoking method '%s' on class '%s'.", f.getName(), o.getClass()), e1); } } return null; }
public static Object doInvokeGetter(Field f, Object o, boolean invokeSize) { PropertyDescriptor pd = null; try { pd = new PropertyDescriptor(f.getName(), o.getClass()); Method readMethod = pd.getReadMethod(); log.debug(">>> GETTER: " + readMethod); Object getterResult = readMethod.invoke(o); // DO NOT REMOVE THE NEXT LINE, SINCE IT HAS TO BE CALLED IN ORDER TO TRIGGER THE LAZY EXCEPTION IF THE CASE getterResult.toString(); // log.debug(">>> getterResult: " + getterResult); // IF o IS A LAZY COLLECTION WE TRIGGER THE EXCEPTION BY CALLING "size()" ON IT if (invokeSize) { Method sizeMethod = getterResult.getClass().getMethod("size"); sizeMethod.invoke(getterResult); } return getterResult; } catch (Throwable e) { Method writeMethod = pd.getWriteMethod(); try { log.debug(">>> SETTER: " + writeMethod); if (isCollection(f.getType())) { if (isSet(f.getType())) writeMethod.invoke(o, new java.util.HashSet()); else writeMethod.invoke(o, new java.util.ArrayList()); } else { Class returnedType = pd.getReadMethod().getReturnType(); writeMethod.invoke(o, returnedType.newInstance()); } } catch (Exception e1) { throw new RuntimeException(String.format("Exception on invoking method '%s' on class '%s'.", f.getName(), o.getClass()), e1); } } return null; }
diff --git a/modules/admin-web/src/main/java/org/openlmis/admin/controller/UploadController.java b/modules/admin-web/src/main/java/org/openlmis/admin/controller/UploadController.java index bdba2f64cc..debf3d7154 100644 --- a/modules/admin-web/src/main/java/org/openlmis/admin/controller/UploadController.java +++ b/modules/admin-web/src/main/java/org/openlmis/admin/controller/UploadController.java @@ -1,58 +1,58 @@ package org.openlmis.admin.controller; import org.openlmis.core.domain.Product; import org.openlmis.core.handler.ProductImportHandler; import org.openlmis.upload.parser.CSVParser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import java.util.HashMap; import java.util.Map; @Controller @RequestMapping("/resources/pages/admin") public class UploadController { private CSVParser csvParser; private ProductImportHandler handler; private final Map<String, Class> modelMap = new HashMap<String, Class>(); @Autowired public UploadController(CSVParser csvParser, ProductImportHandler handler) { this.csvParser = csvParser; this.handler = handler; modelMap.put("product", Product.class); } @RequestMapping(value = "/upload", method = RequestMethod.POST, headers = "Accept=application/json") public ModelAndView upload(@RequestParam(value = "csvFile", required = true) MultipartFile multipartFile, @RequestParam(value = "model", required = true) String model) { ModelAndView modelAndView = new ModelAndView(); try { Class modelClass = modelMap.get(model); if (modelClass == null) { return returnErrorModelAndView(modelAndView, "Incorrect file"); } if (!multipartFile.getOriginalFilename().contains(".csv")) { - return returnErrorModelAndView(modelAndView, "Incorrect file format , Please upload product data as a \".csv\" file"); + return returnErrorModelAndView(modelAndView, "Incorrect file format , Please upload " + model + " data as a \".csv\" file"); } int recordsUploaded = csvParser.process(multipartFile.getInputStream(), modelClass, handler); modelAndView.addObject("message", "File upload success. Total " + model +" uploaded in the system : " + recordsUploaded); } catch (Exception e) { modelAndView.addObject("error", e.getMessage()); } return modelAndView; } private ModelAndView returnErrorModelAndView(ModelAndView modelAndView, String errorMessage) { modelAndView.addObject("error", errorMessage); return modelAndView; } }
true
true
public ModelAndView upload(@RequestParam(value = "csvFile", required = true) MultipartFile multipartFile, @RequestParam(value = "model", required = true) String model) { ModelAndView modelAndView = new ModelAndView(); try { Class modelClass = modelMap.get(model); if (modelClass == null) { return returnErrorModelAndView(modelAndView, "Incorrect file"); } if (!multipartFile.getOriginalFilename().contains(".csv")) { return returnErrorModelAndView(modelAndView, "Incorrect file format , Please upload product data as a \".csv\" file"); } int recordsUploaded = csvParser.process(multipartFile.getInputStream(), modelClass, handler); modelAndView.addObject("message", "File upload success. Total " + model +" uploaded in the system : " + recordsUploaded); } catch (Exception e) { modelAndView.addObject("error", e.getMessage()); } return modelAndView; }
public ModelAndView upload(@RequestParam(value = "csvFile", required = true) MultipartFile multipartFile, @RequestParam(value = "model", required = true) String model) { ModelAndView modelAndView = new ModelAndView(); try { Class modelClass = modelMap.get(model); if (modelClass == null) { return returnErrorModelAndView(modelAndView, "Incorrect file"); } if (!multipartFile.getOriginalFilename().contains(".csv")) { return returnErrorModelAndView(modelAndView, "Incorrect file format , Please upload " + model + " data as a \".csv\" file"); } int recordsUploaded = csvParser.process(multipartFile.getInputStream(), modelClass, handler); modelAndView.addObject("message", "File upload success. Total " + model +" uploaded in the system : " + recordsUploaded); } catch (Exception e) { modelAndView.addObject("error", e.getMessage()); } return modelAndView; }
diff --git a/src/com/example/timetrack/Task.java b/src/com/example/timetrack/Task.java index 91de3d4..ef681cd 100644 --- a/src/com/example/timetrack/Task.java +++ b/src/com/example/timetrack/Task.java @@ -1,300 +1,296 @@ package com.example.timetrack; import android.app.AlertDialog; import android.app.Fragment; import android.app.FragmentManager; import android.os.Bundle; import android.os.Handler; import android.app.FragmentTransaction; import android.content.Context; import android.content.DialogInterface; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Task extends Fragment{ private int id; private String name; private Handler mHandler = new Handler(); private long startTime; private long elapsedTime; private final int REFRESH_RATE = 100; private String hours, minutes, seconds, milliseconds; private long secs, mins, hrs; private boolean stopped = false; private Runnable startTimer = new Runnable() { public void run() { elapsedTime = System.currentTimeMillis() - startTime; updateTimer(elapsedTime); mHandler.postDelayed(this, REFRESH_RATE); } }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflating the layout for this fragment View v = inflater.inflate(R.layout.task_layout, null); // This final Task me = this; // Creating buttons final Button startButton = (Button)v.findViewById(R.id.startButton); final Button stopButton = (Button)v.findViewById(R.id.stopButton); final Button resetButton = (Button)v.findViewById(R.id.resetButton); final Button deleteButton = (Button)v.findViewById(R.id.deleteButton); // Creating button Listeners startButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { showStopButton(); if(stopped){ startTime = System.currentTimeMillis() - elapsedTime; } else{ startTime = System.currentTimeMillis(); } mHandler.removeCallbacks(startTimer); mHandler.postDelayed(startTimer, 0); View v = getView(); v.setBackgroundColor(Color.rgb(32, 156, 57)); - startButton.setBackgroundColor(Color.WHITE); - stopButton.setBackgroundColor(Color.WHITE); - resetButton.setBackgroundColor(Color.WHITE); - deleteButton.setBackgroundColor(Color.WHITE); } }); stopButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { hideStopButton(); mHandler.removeCallbacks(startTimer); stopped = true; View v = getView(); v.setBackgroundColor(Color.rgb(222, 36, 48)); } }); resetButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { stopped = false; View v = getView(); ((TextView)v.findViewById(R.id.timer)).setText("00:00:00"); ((TextView)v.findViewById(R.id.timerMs)).setText(".0"); v.setBackgroundColor(Color.WHITE); } }); // Editing & updating the name final TextView nameText = (TextView)v.findViewById(R.id.name); final EditText editName = (EditText)v.findViewById(R.id.editName); final Button updateButton = (Button)v.findViewById(R.id.updateButton); nameText.setOnClickListener(new OnClickListener() { public void onClick(View view) { showEditText(); editName.setText(nameText.getText().toString()); editName.requestFocus(); } }); updateButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { hideEditText(); setName(editName.getText().toString()); nameText.setText(name); } }); final Context context = getActivity(); // Deleting this fragment deleteButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { switch (which){ case DialogInterface.BUTTON_POSITIVE: //Yes button clicked mHandler.removeCallbacks(startTimer); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.remove(me); fragmentTransaction.commit(); break; case DialogInterface.BUTTON_NEGATIVE: //No button clicked break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage("Are you sure you want to delete this task?").setPositiveButton("Yes", dialogClickListener) .setNegativeButton("No", dialogClickListener).show(); } }); nameText.setText(name); return v; } public int getID() { return id; } public void setID(int id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public long getStartTime() { return this.startTime; } public long getElapsedTime() { return this.elapsedTime; } public boolean getState() { return !stopped; } public void setTime(long startTime, long elapsedTime, boolean notStopped) { stopped = !notStopped; if(stopped) { showStopButton(); startTime = System.currentTimeMillis() - elapsedTime; mHandler.removeCallbacks(startTimer); mHandler.postDelayed(startTimer, 0); } else { hideStopButton(); startTime = System.currentTimeMillis(); mHandler.removeCallbacks(startTimer); } } private void showStopButton(){ View v = getView(); ((Button)v.findViewById(R.id.startButton)).setVisibility(View.GONE); ((Button)v.findViewById(R.id.resetButton)).setVisibility(View.GONE); ((Button)v.findViewById(R.id.stopButton)).setVisibility(View.VISIBLE); } private void hideStopButton(){ View v = getView(); ((Button)v.findViewById(R.id.startButton)).setVisibility(View.VISIBLE); ((Button)v.findViewById(R.id.resetButton)).setVisibility(View.VISIBLE); ((Button)v.findViewById(R.id.stopButton)).setVisibility(View.GONE); } public void showEditText() { View v = getView(); ((EditText)v.findViewById(R.id.editName)).setVisibility(View.VISIBLE); ((Button)v.findViewById(R.id.deleteButton)).setVisibility(View.GONE); ((TextView)v.findViewById(R.id.name)).setVisibility(View.GONE); ((Button)v.findViewById(R.id.updateButton)).setVisibility(View.VISIBLE); } public void hideEditText() { View v = getView(); ((EditText)v.findViewById(R.id.editName)).setVisibility(View.GONE); ((Button)v.findViewById(R.id.deleteButton)).setVisibility(View.VISIBLE); ((TextView)v.findViewById(R.id.name)).setVisibility(View.VISIBLE); ((Button)v.findViewById(R.id.updateButton)).setVisibility(View.GONE); } private void updateTimer (float time){ secs = (long)(time/1000); mins = (long)((time/1000)/60); hrs = (long)(((time/1000)/60)/60); // Convert the seconds to String and format to ensure it has // a leading zero when required secs = secs % 60; seconds=String.valueOf(secs); if(secs == 0){ seconds = "00"; } if(secs <10 && secs > 0){ seconds = "0"+seconds; } // Convert the minutes to String and format the String mins = mins % 60; minutes=String.valueOf(mins); if(mins == 0){ minutes = "00"; } if(mins <10 && mins > 0){ minutes = "0"+minutes; } // Convert the hours to String and format the String hours=String.valueOf(hrs); if(hrs == 0){ hours = "00"; } if(hrs <10 && hrs > 0){ hours = "0"+hours; } // Although we are not using milliseconds on the timer in this example // I included the code in the event that you wanted to include it on your own milliseconds = String.valueOf((long)time); if(milliseconds.length()==2){ milliseconds = "0"+milliseconds; } if(milliseconds.length()<=1){ milliseconds = "00"; } milliseconds = milliseconds.substring(milliseconds.length()-3, milliseconds.length()-2); /* Setting the timer text to the elapsed time */ View v = getView(); ((TextView)v.findViewById(R.id.timer)).setText(hours + ":" + minutes + ":" + seconds); ((TextView)v.findViewById(R.id.timerMs)).setText("." + milliseconds); } /*private String name; private boolean selected; public Task(String name) { this.name = name; selected = false; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isSelected() { return selected; } public void setSelected(boolean selected) { this.selected = selected; }*/ }
true
true
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflating the layout for this fragment View v = inflater.inflate(R.layout.task_layout, null); // This final Task me = this; // Creating buttons final Button startButton = (Button)v.findViewById(R.id.startButton); final Button stopButton = (Button)v.findViewById(R.id.stopButton); final Button resetButton = (Button)v.findViewById(R.id.resetButton); final Button deleteButton = (Button)v.findViewById(R.id.deleteButton); // Creating button Listeners startButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { showStopButton(); if(stopped){ startTime = System.currentTimeMillis() - elapsedTime; } else{ startTime = System.currentTimeMillis(); } mHandler.removeCallbacks(startTimer); mHandler.postDelayed(startTimer, 0); View v = getView(); v.setBackgroundColor(Color.rgb(32, 156, 57)); startButton.setBackgroundColor(Color.WHITE); stopButton.setBackgroundColor(Color.WHITE); resetButton.setBackgroundColor(Color.WHITE); deleteButton.setBackgroundColor(Color.WHITE); } }); stopButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { hideStopButton(); mHandler.removeCallbacks(startTimer); stopped = true; View v = getView(); v.setBackgroundColor(Color.rgb(222, 36, 48)); } }); resetButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { stopped = false; View v = getView(); ((TextView)v.findViewById(R.id.timer)).setText("00:00:00"); ((TextView)v.findViewById(R.id.timerMs)).setText(".0"); v.setBackgroundColor(Color.WHITE); } }); // Editing & updating the name final TextView nameText = (TextView)v.findViewById(R.id.name); final EditText editName = (EditText)v.findViewById(R.id.editName); final Button updateButton = (Button)v.findViewById(R.id.updateButton); nameText.setOnClickListener(new OnClickListener() { public void onClick(View view) { showEditText(); editName.setText(nameText.getText().toString()); editName.requestFocus(); } }); updateButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { hideEditText(); setName(editName.getText().toString()); nameText.setText(name); } }); final Context context = getActivity(); // Deleting this fragment deleteButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { switch (which){ case DialogInterface.BUTTON_POSITIVE: //Yes button clicked mHandler.removeCallbacks(startTimer); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.remove(me); fragmentTransaction.commit(); break; case DialogInterface.BUTTON_NEGATIVE: //No button clicked break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage("Are you sure you want to delete this task?").setPositiveButton("Yes", dialogClickListener) .setNegativeButton("No", dialogClickListener).show(); } }); nameText.setText(name); return v; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflating the layout for this fragment View v = inflater.inflate(R.layout.task_layout, null); // This final Task me = this; // Creating buttons final Button startButton = (Button)v.findViewById(R.id.startButton); final Button stopButton = (Button)v.findViewById(R.id.stopButton); final Button resetButton = (Button)v.findViewById(R.id.resetButton); final Button deleteButton = (Button)v.findViewById(R.id.deleteButton); // Creating button Listeners startButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { showStopButton(); if(stopped){ startTime = System.currentTimeMillis() - elapsedTime; } else{ startTime = System.currentTimeMillis(); } mHandler.removeCallbacks(startTimer); mHandler.postDelayed(startTimer, 0); View v = getView(); v.setBackgroundColor(Color.rgb(32, 156, 57)); } }); stopButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { hideStopButton(); mHandler.removeCallbacks(startTimer); stopped = true; View v = getView(); v.setBackgroundColor(Color.rgb(222, 36, 48)); } }); resetButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { stopped = false; View v = getView(); ((TextView)v.findViewById(R.id.timer)).setText("00:00:00"); ((TextView)v.findViewById(R.id.timerMs)).setText(".0"); v.setBackgroundColor(Color.WHITE); } }); // Editing & updating the name final TextView nameText = (TextView)v.findViewById(R.id.name); final EditText editName = (EditText)v.findViewById(R.id.editName); final Button updateButton = (Button)v.findViewById(R.id.updateButton); nameText.setOnClickListener(new OnClickListener() { public void onClick(View view) { showEditText(); editName.setText(nameText.getText().toString()); editName.requestFocus(); } }); updateButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { hideEditText(); setName(editName.getText().toString()); nameText.setText(name); } }); final Context context = getActivity(); // Deleting this fragment deleteButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { switch (which){ case DialogInterface.BUTTON_POSITIVE: //Yes button clicked mHandler.removeCallbacks(startTimer); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.remove(me); fragmentTransaction.commit(); break; case DialogInterface.BUTTON_NEGATIVE: //No button clicked break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage("Are you sure you want to delete this task?").setPositiveButton("Yes", dialogClickListener) .setNegativeButton("No", dialogClickListener).show(); } }); nameText.setText(name); return v; }
diff --git a/java/TJExample.java b/java/TJExample.java index b9ea34a..a326c71 100644 --- a/java/TJExample.java +++ b/java/TJExample.java @@ -1,308 +1,307 @@ /* * Copyright (C)2011 D. R. Commander. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the libjpeg-turbo Project nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS", * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * This program demonstrates how to compress and decompress JPEG files using * the TurboJPEG JNI wrapper */ import java.io.*; import java.awt.image.*; import javax.imageio.*; import javax.swing.*; import org.libjpegturbo.turbojpeg.*; public class TJExample { public static final String classname = new TJExample().getClass().getName(); private static void usage() throws Exception { System.out.println("\nUSAGE: java " + classname + " <Input file> <Output file> [options]\n"); System.out.println("Input and output files can be any image format that the Java Image I/O"); System.out.println("extensions understand. If either filename ends in a .jpg extension, then"); System.out.println("TurboJPEG will be used to compress or decompress the file.\n"); System.out.println("Options:\n"); System.out.println("-scale M/N = if the input image is a JPEG file, scale the width/height of the"); System.out.print(" output image by a factor of M/N (M/N = "); for(int i = 0; i < sf.length; i++) { System.out.print(sf[i].getNum() + "/" + sf[i].getDenom()); if(sf.length == 2 && i != sf.length - 1) System.out.print(" or "); else if(sf.length > 2) { if(i != sf.length - 1) System.out.print(", "); if(i == sf.length - 2) System.out.print("or "); } } System.out.println(")\n"); System.out.println("-samp <444|422|420|gray> = If the output image is a JPEG file, this specifies"); System.out.println(" the level of chrominance subsampling to use when"); System.out.println(" recompressing it. Default is to use the same level"); System.out.println(" of subsampling as the input, if the input is a JPEG"); System.out.println(" file, or 4:4:4 otherwise.\n"); System.out.println("-q <1-100> = If the output image is a JPEG file, this specifies the JPEG"); System.out.println(" quality to use when recompressing it (default = 95).\n"); System.out.println("-hflip, -vflip, -transpose, -transverse, -rot90, -rot180, -rot270 ="); System.out.println(" If the input image is a JPEG file, perform the corresponding lossless"); System.out.println(" transform prior to decompression (these options are mutually exclusive)\n"); System.out.println("-grayscale = If the input image is a JPEG file, perform lossless grayscale"); System.out.println(" conversion prior to decompression (can be combined with the other"); System.out.println(" transforms above)\n"); System.out.println("-crop X,Y,WxH = If the input image is a JPEG file, perform lossless cropping"); System.out.println(" prior to decompression. X,Y specifies the upper left corner of the"); System.out.println(" cropping region, and WxH specifies its width and height. X,Y must be"); System.out.println(" evenly divible by the MCU block size (8x8 if the source image was"); System.out.println(" compressed using no subsampling or grayscale, or 16x8 for 4:2:2 or 16x16"); System.out.println(" for 4:2:0.)\n"); System.out.println("-display = Display output image (Output file need not be specified in this"); System.out.println(" case.)\n"); System.exit(1); } private final static String sampName[] = { "4:4:4", "4:2:2", "4:2:0", "Grayscale", "4:4:0" }; public static void main(String argv[]) { BufferedImage img = null; byte[] bmpBuf = null; TJTransform xform = new TJTransform(); try { sf = TJ.getScalingFactors(); if(argv.length < 2) { usage(); } TJScalingFactor scaleFactor = new TJScalingFactor(1, 1); String inFormat = "jpg", outFormat = "jpg"; int outSubsamp = -1, outQual = 95; boolean display = false; if(argv.length > 1) { for(int i = 1; i < argv.length; i++) { if(argv[i].length() < 2) continue; if(argv[i].length() > 2 && argv[i].substring(0, 3).equalsIgnoreCase("-sc")) { int match = 0; if(i < argv.length - 1) { - int temp1 = 0, temp2 = 0; String[] scaleArg = argv[++i].split("/"); if(scaleArg.length == 2) { TJScalingFactor tempsf = new TJScalingFactor(Integer.parseInt(scaleArg[0]), Integer.parseInt(scaleArg[1])); for(int j = 0; j < sf.length; j++) { if(tempsf.equals(sf[j])) { scaleFactor = sf[j]; match = 1; break; } } } } if(match != 1) usage(); } if(argv[i].equalsIgnoreCase("-h") || argv[i].equalsIgnoreCase("-?")) usage(); if(argv[i].length() > 2 && argv[i].substring(0, 3).equalsIgnoreCase("-sa")) { if(i < argv.length - 1) { i++; if(argv[i].substring(0, 1).equalsIgnoreCase("g")) outSubsamp = TJ.SAMP_GRAY; else if(argv[i].equals("444")) outSubsamp = TJ.SAMP_444; else if(argv[i].equals("422")) outSubsamp = TJ.SAMP_422; else if(argv[i].equals("420")) outSubsamp = TJ.SAMP_420; else usage(); } else usage(); } if(argv[i].substring(0, 2).equalsIgnoreCase("-q")) { if(i < argv.length - 1) { int qual = Integer.parseInt(argv[++i]); if(qual >= 1 && qual <= 100) outQual = qual; else usage(); } else usage(); } if(argv[i].substring(0, 2).equalsIgnoreCase("-g")) xform.options |= TJTransform.OPT_GRAY; if(argv[i].equalsIgnoreCase("-hflip")) xform.op = TJTransform.OP_HFLIP; if(argv[i].equalsIgnoreCase("-vflip")) xform.op = TJTransform.OP_VFLIP; if(argv[i].equalsIgnoreCase("-transpose")) xform.op = TJTransform.OP_TRANSPOSE; if(argv[i].equalsIgnoreCase("-transverse")) xform.op = TJTransform.OP_TRANSVERSE; if(argv[i].equalsIgnoreCase("-rot90")) xform.op = TJTransform.OP_ROT90; if(argv[i].equalsIgnoreCase("-rot180")) xform.op = TJTransform.OP_ROT180; if(argv[i].equalsIgnoreCase("-rot270")) xform.op = TJTransform.OP_ROT270; if(argv[i].length() > 2 && argv[i].substring(0, 2).equalsIgnoreCase("-c")) { if(i >= argv.length - 1) usage(); String[] cropArg = argv[++i].split(","); if(cropArg.length != 3) usage(); String[] dimArg = cropArg[2].split("[xX]"); if(dimArg.length != 2) usage(); int tempx = Integer.parseInt(cropArg[0]); int tempy = Integer.parseInt(cropArg[1]); int tempw = Integer.parseInt(dimArg[0]); int temph = Integer.parseInt(dimArg[1]); if(tempx < 0 || tempy < 0 || tempw < 0 || temph < 0) usage(); xform.x = tempx; xform.y = tempy; xform.width = tempw; xform.height = temph; xform.options |= TJTransform.OPT_CROP; } if(argv[i].substring(0, 2).equalsIgnoreCase("-d")) display = true; } } String[] inFileTokens = argv[0].split("\\."); if(inFileTokens.length > 1) inFormat = inFileTokens[inFileTokens.length - 1]; String[] outFileTokens; if(display) outFormat = "bmp"; else { outFileTokens = argv[1].split("\\."); if(outFileTokens.length > 1) outFormat = outFileTokens[outFileTokens.length - 1]; } File file = new File(argv[0]); int width, height; if(inFormat.equalsIgnoreCase("jpg")) { FileInputStream fis = new FileInputStream(file); int inputSize = fis.available(); if(inputSize < 1) { System.out.println("Input file contains no data"); System.exit(1); } byte[] inputBuf = new byte[inputSize]; fis.read(inputBuf); fis.close(); TJDecompressor tjd; if(xform.op != TJTransform.OP_NONE || xform.options != 0) { TJTransformer tjt = new TJTransformer(inputBuf); TJTransform t[] = new TJTransform[1]; t[0] = xform; t[0].options |= TJTransform.OPT_TRIM; TJDecompressor[] tjdx = tjt.transform(t, 0); tjd = tjdx[0]; } else tjd = new TJDecompressor(inputBuf); width = tjd.getWidth(); height = tjd.getHeight(); int inSubsamp = tjd.getSubsamp(); System.out.println("Source Image: " + width + " x " + height + " pixels, " + sampName[inSubsamp] + " subsampling"); if(outSubsamp < 0) outSubsamp = inSubsamp; if(outFormat.equalsIgnoreCase("jpg") && (xform.op != TJTransform.OP_NONE || xform.options != 0) && scaleFactor.isOne()) { file = new File(argv[1]); FileOutputStream fos = new FileOutputStream(file); fos.write(tjd.getJPEGBuf(), 0, tjd.getJPEGSize()); fos.close(); System.exit(0); } width = scaleFactor.getScaled(width); height = scaleFactor.getScaled(height); if(!outFormat.equalsIgnoreCase("jpg")) img = tjd.decompress(width, height, BufferedImage.TYPE_INT_RGB, 0); else bmpBuf = tjd.decompress(width, 0, height, TJ.PF_BGRX, 0); tjd.close(); } else { img = ImageIO.read(file); width = img.getWidth(); height = img.getHeight(); if(outSubsamp < 0) { if(img.getType() == BufferedImage.TYPE_BYTE_GRAY) outSubsamp = TJ.SAMP_GRAY; else outSubsamp = TJ.SAMP_444; } } System.gc(); if(!display) System.out.print("Dest. Image (" + outFormat + "): " + width + " x " + height + " pixels"); if(display) { ImageIcon icon = new ImageIcon(img); JLabel label = new JLabel(icon, JLabel.CENTER); JOptionPane.showMessageDialog(null, label, "Output Image", JOptionPane.PLAIN_MESSAGE); } else if(outFormat.equalsIgnoreCase("jpg")) { System.out.println(", " + sampName[outSubsamp] + " subsampling, quality = " + outQual); TJCompressor tjc = new TJCompressor(); int jpegSize; byte[] jpegBuf; tjc.setSubsamp(outSubsamp); tjc.setJPEGQuality(outQual); if(img != null) jpegBuf = tjc.compress(img, 0); else { tjc.setSourceImage(bmpBuf, width, 0, height, TJ.PF_BGRX); jpegBuf = tjc.compress(0); } jpegSize = tjc.getCompressedSize(); tjc.close(); file = new File(argv[1]); FileOutputStream fos = new FileOutputStream(file); fos.write(jpegBuf, 0, jpegSize); fos.close(); } else { System.out.print("\n"); file = new File(argv[1]); ImageIO.write(img, outFormat, file); } } catch(Exception e) { e.printStackTrace(); System.exit(-1); } } static TJScalingFactor sf [] = null; };
true
true
public static void main(String argv[]) { BufferedImage img = null; byte[] bmpBuf = null; TJTransform xform = new TJTransform(); try { sf = TJ.getScalingFactors(); if(argv.length < 2) { usage(); } TJScalingFactor scaleFactor = new TJScalingFactor(1, 1); String inFormat = "jpg", outFormat = "jpg"; int outSubsamp = -1, outQual = 95; boolean display = false; if(argv.length > 1) { for(int i = 1; i < argv.length; i++) { if(argv[i].length() < 2) continue; if(argv[i].length() > 2 && argv[i].substring(0, 3).equalsIgnoreCase("-sc")) { int match = 0; if(i < argv.length - 1) { int temp1 = 0, temp2 = 0; String[] scaleArg = argv[++i].split("/"); if(scaleArg.length == 2) { TJScalingFactor tempsf = new TJScalingFactor(Integer.parseInt(scaleArg[0]), Integer.parseInt(scaleArg[1])); for(int j = 0; j < sf.length; j++) { if(tempsf.equals(sf[j])) { scaleFactor = sf[j]; match = 1; break; } } } } if(match != 1) usage(); } if(argv[i].equalsIgnoreCase("-h") || argv[i].equalsIgnoreCase("-?")) usage(); if(argv[i].length() > 2 && argv[i].substring(0, 3).equalsIgnoreCase("-sa")) { if(i < argv.length - 1) { i++; if(argv[i].substring(0, 1).equalsIgnoreCase("g")) outSubsamp = TJ.SAMP_GRAY; else if(argv[i].equals("444")) outSubsamp = TJ.SAMP_444; else if(argv[i].equals("422")) outSubsamp = TJ.SAMP_422; else if(argv[i].equals("420")) outSubsamp = TJ.SAMP_420; else usage(); } else usage(); } if(argv[i].substring(0, 2).equalsIgnoreCase("-q")) { if(i < argv.length - 1) { int qual = Integer.parseInt(argv[++i]); if(qual >= 1 && qual <= 100) outQual = qual; else usage(); } else usage(); } if(argv[i].substring(0, 2).equalsIgnoreCase("-g")) xform.options |= TJTransform.OPT_GRAY; if(argv[i].equalsIgnoreCase("-hflip")) xform.op = TJTransform.OP_HFLIP; if(argv[i].equalsIgnoreCase("-vflip")) xform.op = TJTransform.OP_VFLIP; if(argv[i].equalsIgnoreCase("-transpose")) xform.op = TJTransform.OP_TRANSPOSE; if(argv[i].equalsIgnoreCase("-transverse")) xform.op = TJTransform.OP_TRANSVERSE; if(argv[i].equalsIgnoreCase("-rot90")) xform.op = TJTransform.OP_ROT90; if(argv[i].equalsIgnoreCase("-rot180")) xform.op = TJTransform.OP_ROT180; if(argv[i].equalsIgnoreCase("-rot270")) xform.op = TJTransform.OP_ROT270; if(argv[i].length() > 2 && argv[i].substring(0, 2).equalsIgnoreCase("-c")) { if(i >= argv.length - 1) usage(); String[] cropArg = argv[++i].split(","); if(cropArg.length != 3) usage(); String[] dimArg = cropArg[2].split("[xX]"); if(dimArg.length != 2) usage(); int tempx = Integer.parseInt(cropArg[0]); int tempy = Integer.parseInt(cropArg[1]); int tempw = Integer.parseInt(dimArg[0]); int temph = Integer.parseInt(dimArg[1]); if(tempx < 0 || tempy < 0 || tempw < 0 || temph < 0) usage(); xform.x = tempx; xform.y = tempy; xform.width = tempw; xform.height = temph; xform.options |= TJTransform.OPT_CROP; } if(argv[i].substring(0, 2).equalsIgnoreCase("-d")) display = true; } } String[] inFileTokens = argv[0].split("\\."); if(inFileTokens.length > 1) inFormat = inFileTokens[inFileTokens.length - 1]; String[] outFileTokens; if(display) outFormat = "bmp"; else { outFileTokens = argv[1].split("\\."); if(outFileTokens.length > 1) outFormat = outFileTokens[outFileTokens.length - 1]; } File file = new File(argv[0]); int width, height; if(inFormat.equalsIgnoreCase("jpg")) { FileInputStream fis = new FileInputStream(file); int inputSize = fis.available(); if(inputSize < 1) { System.out.println("Input file contains no data"); System.exit(1); } byte[] inputBuf = new byte[inputSize]; fis.read(inputBuf); fis.close(); TJDecompressor tjd; if(xform.op != TJTransform.OP_NONE || xform.options != 0) { TJTransformer tjt = new TJTransformer(inputBuf); TJTransform t[] = new TJTransform[1]; t[0] = xform; t[0].options |= TJTransform.OPT_TRIM; TJDecompressor[] tjdx = tjt.transform(t, 0); tjd = tjdx[0]; } else tjd = new TJDecompressor(inputBuf); width = tjd.getWidth(); height = tjd.getHeight(); int inSubsamp = tjd.getSubsamp(); System.out.println("Source Image: " + width + " x " + height + " pixels, " + sampName[inSubsamp] + " subsampling"); if(outSubsamp < 0) outSubsamp = inSubsamp; if(outFormat.equalsIgnoreCase("jpg") && (xform.op != TJTransform.OP_NONE || xform.options != 0) && scaleFactor.isOne()) { file = new File(argv[1]); FileOutputStream fos = new FileOutputStream(file); fos.write(tjd.getJPEGBuf(), 0, tjd.getJPEGSize()); fos.close(); System.exit(0); } width = scaleFactor.getScaled(width); height = scaleFactor.getScaled(height); if(!outFormat.equalsIgnoreCase("jpg")) img = tjd.decompress(width, height, BufferedImage.TYPE_INT_RGB, 0); else bmpBuf = tjd.decompress(width, 0, height, TJ.PF_BGRX, 0); tjd.close(); } else { img = ImageIO.read(file); width = img.getWidth(); height = img.getHeight(); if(outSubsamp < 0) { if(img.getType() == BufferedImage.TYPE_BYTE_GRAY) outSubsamp = TJ.SAMP_GRAY; else outSubsamp = TJ.SAMP_444; } } System.gc(); if(!display) System.out.print("Dest. Image (" + outFormat + "): " + width + " x " + height + " pixels"); if(display) { ImageIcon icon = new ImageIcon(img); JLabel label = new JLabel(icon, JLabel.CENTER); JOptionPane.showMessageDialog(null, label, "Output Image", JOptionPane.PLAIN_MESSAGE); } else if(outFormat.equalsIgnoreCase("jpg")) { System.out.println(", " + sampName[outSubsamp] + " subsampling, quality = " + outQual); TJCompressor tjc = new TJCompressor(); int jpegSize; byte[] jpegBuf; tjc.setSubsamp(outSubsamp); tjc.setJPEGQuality(outQual); if(img != null) jpegBuf = tjc.compress(img, 0); else { tjc.setSourceImage(bmpBuf, width, 0, height, TJ.PF_BGRX); jpegBuf = tjc.compress(0); } jpegSize = tjc.getCompressedSize(); tjc.close(); file = new File(argv[1]); FileOutputStream fos = new FileOutputStream(file); fos.write(jpegBuf, 0, jpegSize); fos.close(); } else { System.out.print("\n"); file = new File(argv[1]); ImageIO.write(img, outFormat, file); } } catch(Exception e) { e.printStackTrace(); System.exit(-1); } }
public static void main(String argv[]) { BufferedImage img = null; byte[] bmpBuf = null; TJTransform xform = new TJTransform(); try { sf = TJ.getScalingFactors(); if(argv.length < 2) { usage(); } TJScalingFactor scaleFactor = new TJScalingFactor(1, 1); String inFormat = "jpg", outFormat = "jpg"; int outSubsamp = -1, outQual = 95; boolean display = false; if(argv.length > 1) { for(int i = 1; i < argv.length; i++) { if(argv[i].length() < 2) continue; if(argv[i].length() > 2 && argv[i].substring(0, 3).equalsIgnoreCase("-sc")) { int match = 0; if(i < argv.length - 1) { String[] scaleArg = argv[++i].split("/"); if(scaleArg.length == 2) { TJScalingFactor tempsf = new TJScalingFactor(Integer.parseInt(scaleArg[0]), Integer.parseInt(scaleArg[1])); for(int j = 0; j < sf.length; j++) { if(tempsf.equals(sf[j])) { scaleFactor = sf[j]; match = 1; break; } } } } if(match != 1) usage(); } if(argv[i].equalsIgnoreCase("-h") || argv[i].equalsIgnoreCase("-?")) usage(); if(argv[i].length() > 2 && argv[i].substring(0, 3).equalsIgnoreCase("-sa")) { if(i < argv.length - 1) { i++; if(argv[i].substring(0, 1).equalsIgnoreCase("g")) outSubsamp = TJ.SAMP_GRAY; else if(argv[i].equals("444")) outSubsamp = TJ.SAMP_444; else if(argv[i].equals("422")) outSubsamp = TJ.SAMP_422; else if(argv[i].equals("420")) outSubsamp = TJ.SAMP_420; else usage(); } else usage(); } if(argv[i].substring(0, 2).equalsIgnoreCase("-q")) { if(i < argv.length - 1) { int qual = Integer.parseInt(argv[++i]); if(qual >= 1 && qual <= 100) outQual = qual; else usage(); } else usage(); } if(argv[i].substring(0, 2).equalsIgnoreCase("-g")) xform.options |= TJTransform.OPT_GRAY; if(argv[i].equalsIgnoreCase("-hflip")) xform.op = TJTransform.OP_HFLIP; if(argv[i].equalsIgnoreCase("-vflip")) xform.op = TJTransform.OP_VFLIP; if(argv[i].equalsIgnoreCase("-transpose")) xform.op = TJTransform.OP_TRANSPOSE; if(argv[i].equalsIgnoreCase("-transverse")) xform.op = TJTransform.OP_TRANSVERSE; if(argv[i].equalsIgnoreCase("-rot90")) xform.op = TJTransform.OP_ROT90; if(argv[i].equalsIgnoreCase("-rot180")) xform.op = TJTransform.OP_ROT180; if(argv[i].equalsIgnoreCase("-rot270")) xform.op = TJTransform.OP_ROT270; if(argv[i].length() > 2 && argv[i].substring(0, 2).equalsIgnoreCase("-c")) { if(i >= argv.length - 1) usage(); String[] cropArg = argv[++i].split(","); if(cropArg.length != 3) usage(); String[] dimArg = cropArg[2].split("[xX]"); if(dimArg.length != 2) usage(); int tempx = Integer.parseInt(cropArg[0]); int tempy = Integer.parseInt(cropArg[1]); int tempw = Integer.parseInt(dimArg[0]); int temph = Integer.parseInt(dimArg[1]); if(tempx < 0 || tempy < 0 || tempw < 0 || temph < 0) usage(); xform.x = tempx; xform.y = tempy; xform.width = tempw; xform.height = temph; xform.options |= TJTransform.OPT_CROP; } if(argv[i].substring(0, 2).equalsIgnoreCase("-d")) display = true; } } String[] inFileTokens = argv[0].split("\\."); if(inFileTokens.length > 1) inFormat = inFileTokens[inFileTokens.length - 1]; String[] outFileTokens; if(display) outFormat = "bmp"; else { outFileTokens = argv[1].split("\\."); if(outFileTokens.length > 1) outFormat = outFileTokens[outFileTokens.length - 1]; } File file = new File(argv[0]); int width, height; if(inFormat.equalsIgnoreCase("jpg")) { FileInputStream fis = new FileInputStream(file); int inputSize = fis.available(); if(inputSize < 1) { System.out.println("Input file contains no data"); System.exit(1); } byte[] inputBuf = new byte[inputSize]; fis.read(inputBuf); fis.close(); TJDecompressor tjd; if(xform.op != TJTransform.OP_NONE || xform.options != 0) { TJTransformer tjt = new TJTransformer(inputBuf); TJTransform t[] = new TJTransform[1]; t[0] = xform; t[0].options |= TJTransform.OPT_TRIM; TJDecompressor[] tjdx = tjt.transform(t, 0); tjd = tjdx[0]; } else tjd = new TJDecompressor(inputBuf); width = tjd.getWidth(); height = tjd.getHeight(); int inSubsamp = tjd.getSubsamp(); System.out.println("Source Image: " + width + " x " + height + " pixels, " + sampName[inSubsamp] + " subsampling"); if(outSubsamp < 0) outSubsamp = inSubsamp; if(outFormat.equalsIgnoreCase("jpg") && (xform.op != TJTransform.OP_NONE || xform.options != 0) && scaleFactor.isOne()) { file = new File(argv[1]); FileOutputStream fos = new FileOutputStream(file); fos.write(tjd.getJPEGBuf(), 0, tjd.getJPEGSize()); fos.close(); System.exit(0); } width = scaleFactor.getScaled(width); height = scaleFactor.getScaled(height); if(!outFormat.equalsIgnoreCase("jpg")) img = tjd.decompress(width, height, BufferedImage.TYPE_INT_RGB, 0); else bmpBuf = tjd.decompress(width, 0, height, TJ.PF_BGRX, 0); tjd.close(); } else { img = ImageIO.read(file); width = img.getWidth(); height = img.getHeight(); if(outSubsamp < 0) { if(img.getType() == BufferedImage.TYPE_BYTE_GRAY) outSubsamp = TJ.SAMP_GRAY; else outSubsamp = TJ.SAMP_444; } } System.gc(); if(!display) System.out.print("Dest. Image (" + outFormat + "): " + width + " x " + height + " pixels"); if(display) { ImageIcon icon = new ImageIcon(img); JLabel label = new JLabel(icon, JLabel.CENTER); JOptionPane.showMessageDialog(null, label, "Output Image", JOptionPane.PLAIN_MESSAGE); } else if(outFormat.equalsIgnoreCase("jpg")) { System.out.println(", " + sampName[outSubsamp] + " subsampling, quality = " + outQual); TJCompressor tjc = new TJCompressor(); int jpegSize; byte[] jpegBuf; tjc.setSubsamp(outSubsamp); tjc.setJPEGQuality(outQual); if(img != null) jpegBuf = tjc.compress(img, 0); else { tjc.setSourceImage(bmpBuf, width, 0, height, TJ.PF_BGRX); jpegBuf = tjc.compress(0); } jpegSize = tjc.getCompressedSize(); tjc.close(); file = new File(argv[1]); FileOutputStream fos = new FileOutputStream(file); fos.write(jpegBuf, 0, jpegSize); fos.close(); } else { System.out.print("\n"); file = new File(argv[1]); ImageIO.write(img, outFormat, file); } } catch(Exception e) { e.printStackTrace(); System.exit(-1); } }
diff --git a/src/main/java/net/aufdemrand/denizen/flags/FlagManager.java b/src/main/java/net/aufdemrand/denizen/flags/FlagManager.java index 1a73d17d0..f58c71f90 100644 --- a/src/main/java/net/aufdemrand/denizen/flags/FlagManager.java +++ b/src/main/java/net/aufdemrand/denizen/flags/FlagManager.java @@ -1,551 +1,551 @@ package net.aufdemrand.denizen.flags; import net.aufdemrand.denizen.Denizen; import net.aufdemrand.denizen.scripts.commands.core.FlagCommand; import net.aufdemrand.denizen.utilities.arguments.aH; import net.aufdemrand.denizen.utilities.debugging.dB; import java.util.ArrayList; import java.util.List; public class FlagManager { private Denizen denizen; public FlagManager(Denizen denizen) { this.denizen = denizen; } /** * When given a FlagType and necessary information, this returns a Flag object. * When getting a FlagType.GLOBAL, targetName/npcid are not necessary and can be * null. When getting a FlagType.PLAYER, npcid is not necessary and can be null. When * getting a FlagType.NPC, targetName is not necessary, as NPC flags * require an npcid instead. If it isn't obvious, flagType and flagName are required. * If this flag currently exists it will be populated with the current values. If * the flag does NOT exist, it will be created with blank values. * * If getting a known specific FlagType, getPlayerFlag(..), getDenizenFlag(..), * or getGlobalFlag(..) may be a cleaner method of retrieval. * */ public Flag getFlag(FlagCommand.Type flagType, String targetName, Integer npcid, String flagName) { if (flagType == FlagCommand.Type.GLOBAL) return new Flag("Global.Flags." + flagName.toUpperCase()); else if (flagType == FlagCommand.Type.PLAYER) return new Flag("Players." + targetName + ".Flags." + flagName.toUpperCase()); else if (flagType == FlagCommand.Type.NPC) return new Flag("NPCs." + npcid + ".Flags." + flagName.toUpperCase()); return new Flag("Global.Flags.null"); } /** * Returns a NPC Flag object. If this flag currently exists * it will be populated with the current values. If the flag does NOT exist, * it will be created with blank values. * */ public Flag getNPCFlag(int npcid, String flagName) { return new Flag("NPCs." + npcid + ".Flags." + flagName.toUpperCase()); } /** * Returns a Global Flag object. If this flag currently exists * it will be populated with the current values. If the flag does NOT exist, * it will be created with blank values. * */ public Flag getGlobalFlag(String flagName) { return new Flag("Global.Flags." + flagName.toUpperCase()); } /** * Returns a Flag Object tied to a Player. If this flag currently exists * it will be populated with the current values. If the flag does NOT exist, * it will be created with blank values. * */ public Flag getPlayerFlag(String playerName, String flagName) { return new Flag("Players." + playerName + ".Flags." + flagName.toUpperCase()); } /** * Flag object contains methods for working with Flags and contain a list * of the values associated with said flag (if existing) and (optionally) an * expiration (if existing). * * Storage example in Denizen saves.yml: * * 'FLAG_NAME': * - First Value * - Second Value * - Third Value * - ... * 'FLAG_NAME-expiration': 123456789 * * To work with multiple values in a flag, an index must be provided. Indexes * start at 1 and get higher as more items are added. Specifying an index of -1, or, * when possible, supplying NO index will result in retrieving/setting/etc the * item with the highest index. Also, note that when using a FLAG TAG in DSCRIPT, * ie. <FLAG.P:FLAG_NAME>, specifying no index will follow suit, that is, the * value with the highest index will be referenced. * */ public class Flag { private Value value; private String flagPath; private long expiration = (long) -1; Flag(String flagPath) { this.flagPath = flagPath; rebuild(); } /** * Returns whether or not a value currently exists in the Flag. The * provided value will check if it matches an existing value by means * of a String.equalsIgnoreCase as well as a Double match if the * provided value is a number. * */ public boolean contains(String stringValue) { checkExpired(); for (String val : value.values) { if (val.equalsIgnoreCase(stringValue)) return true; try { if (Double.valueOf(val).equals(Double.valueOf(stringValue))) return true; } catch (Exception e) { /* Not a valid number, continue. */ } } return false; } /** * Gets all values currently stored in the flag. * */ public List<String> values() { checkExpired(); return value.values; } /** * Gets a specific value stored in a flag when given an index. * */ public Value get(int index) { checkExpired(); return value.get(index); } /** * Clears all values from a flag, essentially making it null. * */ public void clear() { denizen.getSaves().set(flagPath, null); denizen.getSaves().set(flagPath + "-expiration", null); denizen.saveSaves(); rebuild(); } /** * Gets the first value stored in the Flag. * */ public Value getFirst() { checkExpired(); return value.get(1); } /** * Gets the last value stored in the Flag. * */ public Value getLast() { checkExpired(); return value.get(value.size()); } /** * Sets the value of the most recent value added to the flag. This does * not create a new value unless the flag is currently empty of values. * */ public void set(Object obj) { set(obj, -1); } /** * Sets a specific value in the flag. Adds the value to the flag if * the index doesn't exist. If the index is less than 0, it instead * works with the most recent value added to the flag. If the flag is * currently empty, the value is added. * */ public void set(Object obj, int index) { checkExpired(); // No index? Work with last item in the Flag. if (index < 0) index = size(); if (size() == 0) value.values.add((String) obj); else if (index > 0) { if (value.values.size() > index - 1) { value.values.remove(index - 1); value.values.add(index - 1, (String) obj); // Index higher than currently exists? Add the item to the end of the list. } else value.values.add((String) obj); } save(); rebuild(); } /** * Adds a value to the end of the Flag's Values. This value will have an index * of size() + 1. Returns the index of the value added. This could change if * values are removed. * */ public int add(Object obj) { checkExpired(); value.values.add((String) obj); save(); rebuild(); return size(); } /** * Removes a value from the Flag's current values. The first value that matches * (values are checked as Double and String.equalsIgnoreCase) is removed. If * no match, no removal is done. * */ public void remove(Object obj) { remove(obj, -1); } /** * Removes a value from the Flag's current values. If an index is specified, * that specific value is removed. If no index is specified (or -1 is * specified as the index), the first value that matches (values are * checked as Double and String.equalsIgnoreCase) is removed. If a positive * index is specified that does not exist, no removal is done. * */ public void remove(Object obj, int index) { checkExpired(); // No index? Match object and remove it. - if (index < 0 && obj != null) { + if (index <= 0 && obj != null) { int x = 0; for (String val : value.values) { // Evaluate as String - if (val.equalsIgnoreCase((String) obj)) { + if (val.equalsIgnoreCase(String.valueOf(obj))) { value.values.remove(x); return; } // Evaluate as number try { if (Double.valueOf(val).equals(Double.valueOf((String) obj))) { value.values.remove(x); return; } } catch (Exception e) { /* Not a valid number, continue. */ } x++; } // Else, remove specified index } else if (index < size()) value.values.remove(index - 1); save(); rebuild(); } /** * Invalidates the current value/values in the Flag and replaces them with * the object provided. Could be an Integer, String, List<String>, etc. and * in theory, could be anything thats value is easily expressed as a String. * */ public void setEntireValue(Object obj) { denizen.getSaves().set(flagPath, obj); denizen.saveSaves(); rebuild(); } /** * Used to give an expiration time for a flag. This is the same format * as System.getCurrentTimeMillis(), which is the number of milliseconds * since Jan 1, 1960. As an example, to get a valid expiration for a * specific amount of seconds from the current time, use the code snippet * Flag.setExpiration(System.getCurrentTimeMillis() + (delay * 1000)) * where 'delay' is the amount of seconds. * */ public void setExpiration(Long expiration) { this.expiration = expiration; save(); } /** * Returns the number of items in the Flag. This directly corresponds * with the indexes, since Flag Indexes start with 1, unlike Java Lists * which start at 0. * */ public int size() { checkExpired(); return value.size(); } /** * Saves the current values in this object to the Denizen saves.yml. * This is called internally when needed, but might be useful to call * if you are extending the usage of Flags yourself. * */ public void save() { denizen.getSaves().set(flagPath, value.values); denizen.getSaves().set(flagPath + "-expiration", expiration); denizen.saveSaves(); } /** * Returns a String value of the last item in a Flag Value. If there is only * a single item in the flag, it returns it. To return the value of another * item in the Flag, use 'flag.get(index).asString()'. * */ @Override public String toString() { checkExpired(); return value.get(value.size()).asString(); } /** * Removes flag if expiration is found to be up. This is called when an action * is done on the flag, such as get() or put(). If expired, the flag will be * erased before moving on. * */ private void checkExpired() { rebuild(); if (denizen.getSaves().contains(flagPath + "-expiration")) if (expiration > 1 && expiration < System.currentTimeMillis()) { denizen.getSaves().set(flagPath + "-expiration", null); denizen.getSaves().set(flagPath, null); rebuild(); dB.echoDebug("// A FLAG has expired! " + flagPath); } } /** * Rebuilds the flag object with data from the saves.yml (in Memory) * to ensure that data is current if updated outside of the scope * of the plugin. * */ private Flag rebuild() { if (denizen.getSaves().contains(flagPath + "-expiration")) this.expiration = (denizen.getSaves().getLong(flagPath + "-expiration")); List<String> cval = denizen.getSaves().getStringList(flagPath); if (cval == null) { cval = new ArrayList<String>(); cval.add(denizen.getSaves().getString(flagPath, "")); } value = new Value(cval); return this; } } /** * Value object that is in charge of holding values that belong to a flag. * Also contains some methods for retrieving stored values as specific * data types. Otherwise, this object is used internally and created/destroyed * automatically when working with Flag objects. * */ public class Value { private List<String> values; private int index = -1; private Value(List<String> values) { this.values = values; if (this.values == null) { this.values = new ArrayList<String>(); } } /** * Used internally to specify which value to work with, if multiple values * exist. If value is less than 0, value is set to the last value added. * */ private void adjustIndex() { // -1 = last object. if (index < 0) index = size() - 1; } /** * Retrieves a boolean of the value. If the value is set to ANYTHING except * 'FALSE' (equalsIgnoreCase), it will return true. Useful for determining * whether a value exists, as FALSE is also returned if the value is not set. * */ public boolean asBoolean() { adjustIndex(); try { return !values.get(index).equalsIgnoreCase("FALSE"); } catch (Exception e) { return false; } } /** * Retrieves a double value of the specified index. If value is not set, * or the value is not convertible to a Double, 0 is returned. * */ public double asDouble() { adjustIndex(); try { return Double.valueOf(values.get(index)).intValue(); } catch (Exception e) { return 0; } } /** * Returns an Integer value of the specified index. If the value has * decimal point information, it is rounded. If value is not set, * or the value is not convertible to a Double, 0 is returned. * */ public int asInteger() { adjustIndex(); try { return Double.valueOf(values.get(index)).intValue(); } catch (Exception e) { return 0; } } /** * Returns a String value of the entirety of the values * contained as a comma-separated list. If the value doesn't * exist, "" is returned. * */ public String asCommaSeparatedList() { adjustIndex(); String returnList = ""; for (String string : values) returnList = returnList + string + ","; return returnList.substring(0, returnList.length() - 1); } /** * Returns a String value of the entirety of the values * contained as a dScript list. If the value doesn't * exist, "" is returned. * */ public String asList() { adjustIndex(); String returnList = ""; for (String string : values) returnList = returnList + string + "|"; return returnList.substring(0, returnList.length() - 1); } /** * Returns a String value of the value in the specified index. If * the value doesn't exist, "" is returned. * */ public String asString() { adjustIndex(); try { return values.get(index); } catch (Exception e) { return ""; } } /** * Returns an instance of the appropriate Object, as detected by this method. * Should check if instanceof Integer, Double, Boolean, List, or String. * */ public Object asAutoDetectedObject() { adjustIndex(); String arg = values.get(index); try { // If an Integer if (aH.matchesInteger(arg)) return Integer.valueOf(aH.getIntegerFrom(arg)); // If a Double else if (aH.matchesDouble(arg)) return Double.valueOf(aH.getDoubleFrom(arg)); // If a Boolean else if (arg.equalsIgnoreCase("true")) return true; else if (arg.equalsIgnoreCase("false")) return false; // If a List<Object> else if (arg.contains("|")) { List<String> toList = new ArrayList<String>(); for (String string : arg.split("|")) toList.add(string); return toList; } // Must be a String else return arg; } catch (Exception e) { return ""; } } /** * Used internally to specify the index. When using as API, you should * instead use the get(index) method in the Flag object. * */ private Value get(int i) { index = i - 1; adjustIndex(); return this; } /** * Determines if the flag is empty. * */ public boolean isEmpty() { if (values.isEmpty()) return true; adjustIndex(); if (this.size() < index + 1) return true; if (values.get(index).equals("")) return true; return false; } /** * Used internally. Returns the size of the current values list. * */ private int size() { return values.size(); } } }
false
true
public void remove(Object obj, int index) { checkExpired(); // No index? Match object and remove it. if (index < 0 && obj != null) { int x = 0; for (String val : value.values) { // Evaluate as String if (val.equalsIgnoreCase((String) obj)) { value.values.remove(x); return; } // Evaluate as number try { if (Double.valueOf(val).equals(Double.valueOf((String) obj))) { value.values.remove(x); return; } } catch (Exception e) { /* Not a valid number, continue. */ } x++; } // Else, remove specified index } else if (index < size()) value.values.remove(index - 1); save(); rebuild(); }
public void remove(Object obj, int index) { checkExpired(); // No index? Match object and remove it. if (index <= 0 && obj != null) { int x = 0; for (String val : value.values) { // Evaluate as String if (val.equalsIgnoreCase(String.valueOf(obj))) { value.values.remove(x); return; } // Evaluate as number try { if (Double.valueOf(val).equals(Double.valueOf((String) obj))) { value.values.remove(x); return; } } catch (Exception e) { /* Not a valid number, continue. */ } x++; } // Else, remove specified index } else if (index < size()) value.values.remove(index - 1); save(); rebuild(); }
diff --git a/src/web/org/openmrs/web/filter/initialization/InitializationFilter.java b/src/web/org/openmrs/web/filter/initialization/InitializationFilter.java index 23787c9f..84a72abb 100644 --- a/src/web/org/openmrs/web/filter/initialization/InitializationFilter.java +++ b/src/web/org/openmrs/web/filter/initialization/InitializationFilter.java @@ -1,848 +1,850 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.web.filter.initialization; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Writer; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; 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.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.RuntimeConstants; import org.openmrs.ImplementationId; import org.openmrs.api.PasswordException; import org.openmrs.api.context.Context; import org.openmrs.module.web.WebModuleUtil; import org.openmrs.scheduler.SchedulerConstants; import org.openmrs.scheduler.SchedulerUtil; import org.openmrs.util.DatabaseUpdateException; import org.openmrs.util.DatabaseUpdater; import org.openmrs.util.InputRequiredException; import org.openmrs.util.OpenmrsConstants; import org.openmrs.util.OpenmrsUtil; import org.openmrs.web.Listener; import org.openmrs.web.WebConstants; import org.springframework.web.context.ContextLoader; /** * This is the first filter that is processed. It is only active when starting OpenMRS for the very * first time. It will redirect all requests to the {@link WebConstants#SETUP_PAGE_URL} if the * {@link Listener} wasn't able to find any runtime properties */ public class InitializationFilter implements Filter { protected final Log log = LogFactory.getLog(getClass()); private static final String LIQUIBASE_SCHEMA_DATA = "liquibase-schema-only.xml"; private static final String LIQUIBASE_CORE_DATA = "liquibase-core-data.xml"; private static final String LIQUIBASE_DEMO_DATA = "liquibase-demo-data.xml"; private static VelocityEngine velocityEngine = null; /** * The velocity macro page to redirect to if an error occurs or on initial startup */ private final String DEFAULT_PAGE = "databasesetup.vm"; /** * Set by the {@link #init(FilterConfig)} method so that we have access to the current * {@link ServletContext} */ private FilterConfig filterConfig = null; /** * The model object that holds all the properties that the rendered templates use. All * attributes on this object are made available to all templates via reflection in the * {@link #renderTemplate(String, Map, Writer)} method. */ private InitializationWizardModel wizardModel = null; /** * Variable set at the end of the wizard when spring is being restarted */ private boolean initializationComplete = false; /** * The web.xml file sets this {@link InitializationFilter} to be the first filter for all * requests. * * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (Listener.runtimePropertiesFound() || isInitializationComplete()) { chain.doFilter(request, response); } else { // we only get here if the Listener didn't find a runtime // properties files HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String servletPath = httpRequest.getServletPath(); // for all /images files, write the path if (servletPath.startsWith("/images") || servletPath.startsWith("/scripts")) { // writes the actual image file path to the response File file = new File(filterConfig.getServletContext().getRealPath(httpRequest.getServletPath())); if (httpRequest.getPathInfo() != null) file = new File(file, httpRequest.getPathInfo()); try { InputStream imageFileInputStream = new FileInputStream(file); OpenmrsUtil.copyFile(imageFileInputStream, httpResponse.getOutputStream()); imageFileInputStream.close(); } catch (FileNotFoundException e) { log.error("Unable to find file: " + file.getAbsolutePath()); } } // for anything but /initialsetup else if (!httpRequest.getServletPath().equals("/" + WebConstants.SETUP_PAGE_URL)) { // send the user to the setup page httpResponse.sendRedirect("/" + WebConstants.WEBAPP_NAME + "/" + WebConstants.SETUP_PAGE_URL); } else { // does the wizard // clear the error message that was potentially there from // the last page wizardModel.workLog.clear(); wizardModel.errors.clear(); if (httpRequest.getMethod().equals("GET")) { doGet(httpRequest, httpResponse); } else if (httpRequest.getMethod().equals("POST")) { doPost(httpRequest, httpResponse); } } // Don't continue down the filter chain otherwise Spring complains // that it hasn't been set up yet. // The jsp and servlet filter are also on this chain, so writing to // the response directly here is the only option } } /** * Convenience method to set up the velocity context properly */ private void initializeVelocity() { if (velocityEngine == null) { velocityEngine = new VelocityEngine(); Properties props = new Properties(); props.setProperty(RuntimeConstants.RUNTIME_LOG, "initial_wizard_vel.log"); // props.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, // "org.apache.velocity.runtime.log.CommonsLogLogChute" ); // props.setProperty(CommonsLogLogChute.LOGCHUTE_COMMONS_LOG_NAME, // "initial_wizard_velocity"); // so the vm pages can import the header/footer props.setProperty(RuntimeConstants.RESOURCE_LOADER, "class"); props.setProperty("class.resource.loader.description", "Velocity Classpath Resource Loader"); props.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); try { velocityEngine.init(props); } catch (Exception e) { log.error("velocity init failed, because: " + e); } } } /** * Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on GET requests * * @param httpRequest * @param httpResponse */ private void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException { Writer writer = httpResponse.getWriter(); Map<String, Object> referenceMap = new HashMap<String, Object>(); File runtimeProperties = getRuntimePropertiesFile(); if (!runtimeProperties.exists()) { try { runtimeProperties.createNewFile(); } catch (IOException io) { wizardModel.canCreate = false; wizardModel.cannotCreateErrorMessage = io.getMessage(); } // check this before deleting the file again wizardModel.canWrite = runtimeProperties.canWrite(); // delete the file again after testing the create/write // so that if the user stops the webapp before finishing // this wizard, they can still get back into it runtimeProperties.delete(); } else { wizardModel.canWrite = runtimeProperties.canWrite(); } wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath(); // do step one of the wizard renderTemplate(DEFAULT_PAGE, referenceMap, writer); } /** * Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on POST requests * * @param httpRequest * @param httpResponse */ private void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException { String page = httpRequest.getParameter("page"); Map<String, Object> referenceMap = new HashMap<String, Object>(); Writer writer = httpResponse.getWriter(); // clear existing errors wizardModel.errors.clear(); // step one if ("databasesetup.vm".equals(page)) { wizardModel.databaseConnection = httpRequest.getParameter("database_connection"); checkForEmptyValue(wizardModel.databaseConnection, wizardModel.errors, "Database connection string"); // asked the user for their desired database name if ("yes".equals(httpRequest.getParameter("current_openmrs_database"))) { wizardModel.databaseName = httpRequest.getParameter("openmrs_current_database_name"); checkForEmptyValue(wizardModel.databaseName, wizardModel.errors, "Current database name"); wizardModel.hasCurrentOpenmrsDatabase = true; // TODO check to see if this is an active database } else { // mark this wizard as a "to create database" (done at the end) wizardModel.hasCurrentOpenmrsDatabase = false; wizardModel.createTables = true; wizardModel.databaseName = httpRequest.getParameter("openmrs_new_database_name"); checkForEmptyValue(wizardModel.databaseName, wizardModel.errors, "New database name"); // TODO create database now to check if its possible? wizardModel.createDatabaseUsername = httpRequest.getParameter("create_database_username"); checkForEmptyValue(wizardModel.createDatabaseUsername, wizardModel.errors, "A user that has 'CREATE DATABASE' privileges"); wizardModel.createDatabasePassword = httpRequest.getParameter("create_database_password"); checkForEmptyValue(wizardModel.createDatabasePassword, wizardModel.errors, "Password for user with 'CREATE DATABASE' privileges"); } if (wizardModel.errors.isEmpty()) { page = "databasetablesanduser.vm"; } renderTemplate(page, referenceMap, writer); } // step two else if ("databasetablesanduser.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { renderTemplate("databasesetup.vm", referenceMap, writer); return; } if (wizardModel.hasCurrentOpenmrsDatabase) { wizardModel.createTables = "yes".equals(httpRequest.getParameter("create_tables")); } wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data")); if ("yes".equals(httpRequest.getParameter("current_database_user"))) { wizardModel.currentDatabaseUsername = httpRequest.getParameter("current_database_username"); checkForEmptyValue(wizardModel.currentDatabaseUsername, wizardModel.errors, "Curent user account"); wizardModel.currentDatabasePassword = httpRequest.getParameter("current_database_password"); checkForEmptyValue(wizardModel.currentDatabasePassword, wizardModel.errors, "Current user account password"); wizardModel.hasCurrentDatabaseUser = true; wizardModel.createDatabaseUser = false; } else { wizardModel.hasCurrentDatabaseUser = false; wizardModel.createDatabaseUser = true; // asked for the root mysql username/password wizardModel.createUserUsername = httpRequest.getParameter("create_user_username"); checkForEmptyValue(wizardModel.createUserUsername, wizardModel.errors, "A user that has 'CREATE USER' privileges"); wizardModel.createUserPassword = httpRequest.getParameter("create_user_password"); checkForEmptyValue(wizardModel.createUserPassword, wizardModel.errors, "Password for user that has 'CREATE USER' privileges"); } if (wizardModel.errors.isEmpty()) { // go to next page page = "otherruntimeproperties.vm"; } renderTemplate(page, referenceMap, writer); } // step three else if ("otherruntimeproperties.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { renderTemplate("databasetablesanduser.vm", referenceMap, writer); return; } wizardModel.moduleWebAdmin = "yes".equals(httpRequest.getParameter("module_web_admin")); wizardModel.autoUpdateDatabase = "yes".equals(httpRequest.getParameter("auto_update_database")); if (wizardModel.createTables) { // go to next page if they are creating tables page = "adminusersetup.vm"; } else { // skip a page page = "implementationidsetup.vm"; } renderTemplate(page, referenceMap, writer); } // optional step four else if ("adminusersetup.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { renderTemplate("otherruntimeproperties.vm", referenceMap, writer); return; } wizardModel.adminUserPassword = httpRequest.getParameter("new_admin_password"); String adminUserConfirm = httpRequest.getParameter("new_admin_password_confirm"); // throw back to admin user if passwords don't match if (!wizardModel.adminUserPassword.equals(adminUserConfirm)) { wizardModel.errors.add("Admin passwords don't match"); renderTemplate("adminusersetup.vm", referenceMap, writer); return; } // throw back if the user didn't put in a password if (wizardModel.adminUserPassword.equals("")) { wizardModel.errors.add("An admin password is required"); renderTemplate("adminusersetup.vm", referenceMap, writer); return; } try { OpenmrsUtil.validatePassword("admin", wizardModel.adminUserPassword, "admin"); } catch (PasswordException p) { wizardModel.errors.add("The password is not long enough, does not contain both uppercase characters and a number, or matches the username."); renderTemplate("adminusersetup.vm", referenceMap, writer); return; } if (wizardModel.errors.isEmpty()) { // go to next page page = "implementationidsetup.vm"; } renderTemplate(page, referenceMap, writer); } // optional step five else if ("implementationidsetup.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { if (wizardModel.createTables) renderTemplate("adminusersetup.vm", referenceMap, writer); else renderTemplate("otherruntimeproperties.vm", referenceMap, writer); return; } wizardModel.implementationIdName = httpRequest.getParameter("implementation_name"); wizardModel.implementationId = httpRequest.getParameter("implementation_id"); wizardModel.implementationIdPassPhrase = httpRequest.getParameter("pass_phrase"); wizardModel.implementationIdDescription = httpRequest.getParameter("description"); // throw back if the user-specified ID is invalid (contains ^ or |). if (wizardModel.implementationId.indexOf('^') != -1 || wizardModel.implementationId.indexOf('|') != -1) { wizardModel.errors.add("Implementation ID cannot contain '^' or '|'"); renderTemplate("implementationidsetup.vm", referenceMap, writer); return; } if (wizardModel.errors.isEmpty()) { // go to next page page = "wizardcomplete.vm"; } renderTemplate(page, referenceMap, writer); } else if ("wizardcomplete.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { renderTemplate("implementationidsetup.vm", referenceMap, writer); return; } Properties runtimeProperties = new Properties(); String connectionUsername; String connectionPassword; if (!wizardModel.hasCurrentOpenmrsDatabase) { // connect via jdbc and create a database String sql = "create database `?` default character set utf8"; int result = executeStatement(false, wizardModel.createDatabaseUsername, wizardModel.createDatabasePassword, sql, wizardModel.databaseName); // throw the user back to the main screen if this error occurs if (result < 0) { renderTemplate(DEFAULT_PAGE, null, writer); return; } else { wizardModel.workLog.add("Created database " + wizardModel.databaseName); } } if (wizardModel.createDatabaseUser) { connectionUsername = wizardModel.databaseName + "_user"; if (connectionUsername.length() > 16) connectionUsername = wizardModel.databaseName.substring(0, 11) + "_user"; // trim off enough to leave space for _user at the end connectionPassword = ""; // generate random password from this subset of alphabet // intentionally left out these characters: ufsb$() to prevent certain words forming randomly String chars = "acdeghijklmnopqrtvwxyzACDEGHIJKLMNOPQRTVWXYZ0123456789.|~@#^&"; Random r = new Random(); for (int x = 0; x < 12; x++) { connectionPassword += chars.charAt(r.nextInt(chars.length())); } // connect via jdbc with root user and create an openmrs user String sql = "drop user '?'@'localhost'"; executeStatement(true, wizardModel.createUserUsername, wizardModel.createUserPassword, sql, connectionUsername); sql = "create user '?'@'localhost' identified by '?'"; if (-1 != executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword, sql, connectionUsername, connectionPassword)) { wizardModel.workLog.add("Created user " + connectionUsername); } else { // if error occurs stop renderTemplate(DEFAULT_PAGE, null, writer); return; } // grant the roles sql = "GRANT ALL ON `?`.* TO '?'@'localhost'"; int result = executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword, sql, wizardModel.databaseName, connectionUsername); // throw the user back to the main screen if this error occurs if (result < 0) { renderTemplate(DEFAULT_PAGE, null, writer); return; } else { wizardModel.workLog.add("Granted user " + connectionUsername + " all privileges to database " + wizardModel.databaseName); } } else { connectionUsername = wizardModel.currentDatabaseUsername; connectionPassword = wizardModel.currentDatabasePassword; } String finalDatabaseConnectionString = wizardModel.databaseConnection.replace("@DBNAME@", wizardModel.databaseName); // verify that the database connection works if (!verifyConnection(connectionUsername, connectionPassword, finalDatabaseConnectionString)) { // redirect to setup page if we got an error renderTemplate(DEFAULT_PAGE, null, writer); return; } // save the properties for startup purposes runtimeProperties.put("connection.url", finalDatabaseConnectionString); runtimeProperties.put("connection.username", connectionUsername); runtimeProperties.put("connection.password", connectionPassword); runtimeProperties.put("module.allow_web_admin", wizardModel.moduleWebAdmin.toString()); runtimeProperties.put("auto_update_database", wizardModel.autoUpdateDatabase.toString()); runtimeProperties.put(SchedulerConstants.SCHEDULER_USERNAME_PROPERTY, "admin"); runtimeProperties.put(SchedulerConstants.SCHEDULER_PASSWORD_PROPERTY, wizardModel.adminUserPassword); Context.setRuntimeProperties(runtimeProperties); if (wizardModel.createTables) { // use liquibase to create core data + tables try { DatabaseUpdater.executeChangelog(LIQUIBASE_SCHEMA_DATA, null); DatabaseUpdater.executeChangelog(LIQUIBASE_CORE_DATA, null); wizardModel.workLog.add("Created database tables and added core data"); } catch (Exception e) { wizardModel.errors.add(e.getMessage() + " See the error log for more details"); // TODO internationalize this log.warn("Error while trying to create tables and demo data", e); } } // add demo data only if creating tables fresh and user selected the option add demo data if (wizardModel.createTables && wizardModel.addDemoData) { try { DatabaseUpdater.executeChangelog(LIQUIBASE_DEMO_DATA, null); wizardModel.workLog.add("Added demo data"); } catch (Exception e) { wizardModel.errors.add(e.getMessage() + " See the error log for more details"); // TODO internationalize this log.warn("Error while trying to add demo data", e); } } // update the database to the latest version try { DatabaseUpdater.update(); } catch (Exception e) { wizardModel.errors.add(e.getMessage() + " Error while trying to update to the latest database version"); // TODO internationalize this log.warn("Error while trying to update to the latest database version", e); renderTemplate(DEFAULT_PAGE, null, writer); return; } // start spring // after this point, all errors need to also call: contextLoader.closeWebApplicationContext(event.getServletContext()) // logic copied from org.springframework.web.context.ContextLoaderListener ContextLoader contextLoader = new ContextLoader(); contextLoader.initWebApplicationContext(filterConfig.getServletContext()); // start openmrs try { + Context.openSession(); Context.startup(runtimeProperties); } catch (DatabaseUpdateException updateEx) { log.warn("Error while running the database update file", updateEx); wizardModel.errors.add(updateEx.getMessage() + " There was an error while running the database update file: " + updateEx.getMessage()); // TODO internationalize this renderTemplate(DEFAULT_PAGE, null, writer); return; } catch (InputRequiredException inputRequiredEx) { // TODO display a page looping over the required input and ask the user for each. // When done and the user and put in their say, call DatabaseUpdater.update(Map); // with the user's question/answer pairs log .warn("Unable to continue because user input is required for the db updates, but I am not doing anything about that right now"); wizardModel.errors .add("Unable to continue because user input is required for the db updates, but I am not doing anything about that right now"); renderTemplate(DEFAULT_PAGE, null, writer); return; } // TODO catch openmrs errors here and drop the user back out to the setup screen if (!wizardModel.implementationId.equals("")) { try { Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_GLOBAL_PROPERTIES); Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_CONCEPT_SOURCES); Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_SOURCES); ImplementationId implId = new ImplementationId(); implId.setName(wizardModel.implementationIdName); implId.setImplementationId(wizardModel.implementationId); implId.setPassphrase(wizardModel.implementationIdPassPhrase); implId.setDescription(wizardModel.implementationIdDescription); Context.getAdministrationService().setImplementationId(implId); } catch (Throwable t) { wizardModel.errors.add(t.getMessage() + " Implementation ID could not be set."); log.warn("Implementation ID could not be set.", t); renderTemplate(DEFAULT_PAGE, null, writer); Context.shutdown(); WebModuleUtil.shutdownModules(filterConfig.getServletContext()); contextLoader.closeWebApplicationContext(filterConfig.getServletContext()); return; } finally { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_GLOBAL_PROPERTIES); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_CONCEPT_SOURCES); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_SOURCES); } } try { // change the admin user password from "test" to what they input above if (wizardModel.createTables) { Context.authenticate("admin", "test"); Context.getUserService().changePassword("test", wizardModel.adminUserPassword); Context.logout(); } // load modules Listener.loadCoreModules(filterConfig.getServletContext()); // web load modules Listener.performWebStartOfModules(filterConfig.getServletContext()); // start the scheduled tasks SchedulerUtil.startup(runtimeProperties); } catch (Throwable t) { Context.shutdown(); WebModuleUtil.shutdownModules(filterConfig.getServletContext()); contextLoader.closeWebApplicationContext(filterConfig.getServletContext()); wizardModel.errors.add(t.getMessage() + " Unable to complete the startup."); log.warn("Unable to complete the startup.", t); renderTemplate(DEFAULT_PAGE, null, writer); return; } // output properties to the openmrs runtime properties file so that this wizard is not run again FileOutputStream fos = null; try { fos = new FileOutputStream(getRuntimePropertiesFile()); runtimeProperties.store(fos, "Auto generated by OpenMRS initialization wizard"); wizardModel.workLog.add("Saved runtime properties file " + getRuntimePropertiesFile()); // don't need to catch errors here because we tested it at the beginning of the wizard } finally { if (fos != null) { fos.close(); } } // set this so that the wizard isn't run again on next page load initializationComplete = true; + Context.closeSession(); // TODO send user to confirmation page with results of wizard, location of runtime props, etc instead? httpResponse.sendRedirect("/" + WebConstants.WEBAPP_NAME); } } /** * Verify the database connection works. * * @param connectionUsername * @param connectionPassword * @param databaseConnectionFinalUrl * @return true/false whether it was verified or not */ private boolean verifyConnection(String connectionUsername, String connectionPassword, String databaseConnectionFinalUrl) { try { // verify connection // TODO how to get the driver for the other dbs... Class.forName("com.mysql.jdbc.Driver").newInstance(); DriverManager.getConnection(databaseConnectionFinalUrl, connectionUsername, connectionPassword); return true; } catch (Exception e) { wizardModel.errors.add("User account " + connectionUsername + " does not work. " + e.getMessage() + " See the error log for more details"); // TODO internationalize this log.warn("Error while checking the connection user account", e); return false; } } /** * Convenience method to load the runtime properties in the application data directory * * @return */ private File getRuntimePropertiesFile() { String filename = WebConstants.WEBAPP_NAME + "-runtime.properties"; File file = new File(OpenmrsUtil.getApplicationDataDirectory(), filename); log.debug("Using file: " + file.getAbsolutePath()); return file; } /** * All private attributes on this class are returned to the template via the velocity context * and reflection * * @param templateName * @param referenceMap * @param writer */ private void renderTemplate(String templateName, Map<String, Object> referenceMap, Writer writer) throws IOException { VelocityContext velocityContext = new VelocityContext(); if (referenceMap != null) { for (Map.Entry<String, Object> entry : referenceMap.entrySet()) { velocityContext.put(entry.getKey(), entry.getValue()); } } // put each of the private varibles into the template for convenience for (Field field : InitializationWizardModel.class.getDeclaredFields()) { try { velocityContext.put(field.getName(), field.get(wizardModel)); } catch (IllegalArgumentException e) { log.error("Error generated while getting field value: " + field.getName(), e); } catch (IllegalAccessException e) { log.error("Error generated while getting field value: " + field.getName(), e); } } String fullTemplatePath = "org/openmrs/web/filter/initialization/" + templateName; InputStream templateInputStream = getClass().getClassLoader().getResourceAsStream(fullTemplatePath); if (templateInputStream == null) { throw new IOException("Unable to find " + fullTemplatePath); } try { velocityEngine.evaluate(velocityContext, writer, this.getClass().getName(), new InputStreamReader( templateInputStream)); } catch (Exception e) { throw new RuntimeException("Unable to process template: " + fullTemplatePath, e); } } /** * @see javax.servlet.Filter#destroy() */ public void destroy() { } /** * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) */ public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; initializeVelocity(); wizardModel = new InitializationWizardModel(); } /** * @param silent if this statement fails do not display stack trace or record an error in the * wizard object. * @param user username to connect with * @param pw password to connect with * @param sql String containing sql and question marks * @param args the strings to fill into the question marks in the given sql * @return result of executeUpdate or -1 for error */ private int executeStatement(boolean silent, String user, String pw, String sql, String... args) { Connection connection = null; try { String replacedSql = sql; // TODO how to get the driver for the other dbs... if (wizardModel.databaseConnection.contains("mysql")) { Class.forName("com.mysql.jdbc.Driver").newInstance(); } else { replacedSql = replacedSql.replaceAll("`", "\""); } String tempDatabaseConnection = ""; if (sql.contains("create database")) { tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@", ""); // make this dbname agnostic so we can create the db } else { tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@", wizardModel.databaseName); } connection = DriverManager.getConnection(tempDatabaseConnection, user, pw); for (String arg : args) { arg = arg.replace(";", "&#094"); // to prevent any sql injection replacedSql = replacedSql.replaceFirst("\\?", arg); } // run the sql statement Statement statement = connection.createStatement(); return statement.executeUpdate(replacedSql); } catch (SQLException sqlex) { if (!silent) { // log and add error log.warn("error executing sql: " + sql, sqlex); wizardModel.errors.add("Error executing sql: " + sql + " - " + sqlex.getMessage()); } } catch (InstantiationException e) { log.error("Error generated", e); } catch (IllegalAccessException e) { log.error("Error generated", e); } catch (ClassNotFoundException e) { log.error("Error generated", e); } finally { try { if (connection != null) { connection.close(); } } catch (Throwable t) { log.warn("Error while closing connection", t); } } return -1; } /** * Convenience variable to know if this wizard has completed successfully and that this wizard * does not need to be executed again * * @return */ private boolean isInitializationComplete() { return initializationComplete; } /** * Check if the given value is null or a zero-length String * * @param value the string to check * @param errors the list of errors to append the errorMessage to if value is empty * @param errorMessage the string error message to append if value is empty * @return true if the value is non-empty */ private boolean checkForEmptyValue(String value, List<String> errors, String errorMessage) { if (value != null && !value.equals("")) { return true; } errors.add(errorMessage + " required."); return false; } }
false
true
private void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException { String page = httpRequest.getParameter("page"); Map<String, Object> referenceMap = new HashMap<String, Object>(); Writer writer = httpResponse.getWriter(); // clear existing errors wizardModel.errors.clear(); // step one if ("databasesetup.vm".equals(page)) { wizardModel.databaseConnection = httpRequest.getParameter("database_connection"); checkForEmptyValue(wizardModel.databaseConnection, wizardModel.errors, "Database connection string"); // asked the user for their desired database name if ("yes".equals(httpRequest.getParameter("current_openmrs_database"))) { wizardModel.databaseName = httpRequest.getParameter("openmrs_current_database_name"); checkForEmptyValue(wizardModel.databaseName, wizardModel.errors, "Current database name"); wizardModel.hasCurrentOpenmrsDatabase = true; // TODO check to see if this is an active database } else { // mark this wizard as a "to create database" (done at the end) wizardModel.hasCurrentOpenmrsDatabase = false; wizardModel.createTables = true; wizardModel.databaseName = httpRequest.getParameter("openmrs_new_database_name"); checkForEmptyValue(wizardModel.databaseName, wizardModel.errors, "New database name"); // TODO create database now to check if its possible? wizardModel.createDatabaseUsername = httpRequest.getParameter("create_database_username"); checkForEmptyValue(wizardModel.createDatabaseUsername, wizardModel.errors, "A user that has 'CREATE DATABASE' privileges"); wizardModel.createDatabasePassword = httpRequest.getParameter("create_database_password"); checkForEmptyValue(wizardModel.createDatabasePassword, wizardModel.errors, "Password for user with 'CREATE DATABASE' privileges"); } if (wizardModel.errors.isEmpty()) { page = "databasetablesanduser.vm"; } renderTemplate(page, referenceMap, writer); } // step two else if ("databasetablesanduser.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { renderTemplate("databasesetup.vm", referenceMap, writer); return; } if (wizardModel.hasCurrentOpenmrsDatabase) { wizardModel.createTables = "yes".equals(httpRequest.getParameter("create_tables")); } wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data")); if ("yes".equals(httpRequest.getParameter("current_database_user"))) { wizardModel.currentDatabaseUsername = httpRequest.getParameter("current_database_username"); checkForEmptyValue(wizardModel.currentDatabaseUsername, wizardModel.errors, "Curent user account"); wizardModel.currentDatabasePassword = httpRequest.getParameter("current_database_password"); checkForEmptyValue(wizardModel.currentDatabasePassword, wizardModel.errors, "Current user account password"); wizardModel.hasCurrentDatabaseUser = true; wizardModel.createDatabaseUser = false; } else { wizardModel.hasCurrentDatabaseUser = false; wizardModel.createDatabaseUser = true; // asked for the root mysql username/password wizardModel.createUserUsername = httpRequest.getParameter("create_user_username"); checkForEmptyValue(wizardModel.createUserUsername, wizardModel.errors, "A user that has 'CREATE USER' privileges"); wizardModel.createUserPassword = httpRequest.getParameter("create_user_password"); checkForEmptyValue(wizardModel.createUserPassword, wizardModel.errors, "Password for user that has 'CREATE USER' privileges"); } if (wizardModel.errors.isEmpty()) { // go to next page page = "otherruntimeproperties.vm"; } renderTemplate(page, referenceMap, writer); } // step three else if ("otherruntimeproperties.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { renderTemplate("databasetablesanduser.vm", referenceMap, writer); return; } wizardModel.moduleWebAdmin = "yes".equals(httpRequest.getParameter("module_web_admin")); wizardModel.autoUpdateDatabase = "yes".equals(httpRequest.getParameter("auto_update_database")); if (wizardModel.createTables) { // go to next page if they are creating tables page = "adminusersetup.vm"; } else { // skip a page page = "implementationidsetup.vm"; } renderTemplate(page, referenceMap, writer); } // optional step four else if ("adminusersetup.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { renderTemplate("otherruntimeproperties.vm", referenceMap, writer); return; } wizardModel.adminUserPassword = httpRequest.getParameter("new_admin_password"); String adminUserConfirm = httpRequest.getParameter("new_admin_password_confirm"); // throw back to admin user if passwords don't match if (!wizardModel.adminUserPassword.equals(adminUserConfirm)) { wizardModel.errors.add("Admin passwords don't match"); renderTemplate("adminusersetup.vm", referenceMap, writer); return; } // throw back if the user didn't put in a password if (wizardModel.adminUserPassword.equals("")) { wizardModel.errors.add("An admin password is required"); renderTemplate("adminusersetup.vm", referenceMap, writer); return; } try { OpenmrsUtil.validatePassword("admin", wizardModel.adminUserPassword, "admin"); } catch (PasswordException p) { wizardModel.errors.add("The password is not long enough, does not contain both uppercase characters and a number, or matches the username."); renderTemplate("adminusersetup.vm", referenceMap, writer); return; } if (wizardModel.errors.isEmpty()) { // go to next page page = "implementationidsetup.vm"; } renderTemplate(page, referenceMap, writer); } // optional step five else if ("implementationidsetup.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { if (wizardModel.createTables) renderTemplate("adminusersetup.vm", referenceMap, writer); else renderTemplate("otherruntimeproperties.vm", referenceMap, writer); return; } wizardModel.implementationIdName = httpRequest.getParameter("implementation_name"); wizardModel.implementationId = httpRequest.getParameter("implementation_id"); wizardModel.implementationIdPassPhrase = httpRequest.getParameter("pass_phrase"); wizardModel.implementationIdDescription = httpRequest.getParameter("description"); // throw back if the user-specified ID is invalid (contains ^ or |). if (wizardModel.implementationId.indexOf('^') != -1 || wizardModel.implementationId.indexOf('|') != -1) { wizardModel.errors.add("Implementation ID cannot contain '^' or '|'"); renderTemplate("implementationidsetup.vm", referenceMap, writer); return; } if (wizardModel.errors.isEmpty()) { // go to next page page = "wizardcomplete.vm"; } renderTemplate(page, referenceMap, writer); } else if ("wizardcomplete.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { renderTemplate("implementationidsetup.vm", referenceMap, writer); return; } Properties runtimeProperties = new Properties(); String connectionUsername; String connectionPassword; if (!wizardModel.hasCurrentOpenmrsDatabase) { // connect via jdbc and create a database String sql = "create database `?` default character set utf8"; int result = executeStatement(false, wizardModel.createDatabaseUsername, wizardModel.createDatabasePassword, sql, wizardModel.databaseName); // throw the user back to the main screen if this error occurs if (result < 0) { renderTemplate(DEFAULT_PAGE, null, writer); return; } else { wizardModel.workLog.add("Created database " + wizardModel.databaseName); } } if (wizardModel.createDatabaseUser) { connectionUsername = wizardModel.databaseName + "_user"; if (connectionUsername.length() > 16) connectionUsername = wizardModel.databaseName.substring(0, 11) + "_user"; // trim off enough to leave space for _user at the end connectionPassword = ""; // generate random password from this subset of alphabet // intentionally left out these characters: ufsb$() to prevent certain words forming randomly String chars = "acdeghijklmnopqrtvwxyzACDEGHIJKLMNOPQRTVWXYZ0123456789.|~@#^&"; Random r = new Random(); for (int x = 0; x < 12; x++) { connectionPassword += chars.charAt(r.nextInt(chars.length())); } // connect via jdbc with root user and create an openmrs user String sql = "drop user '?'@'localhost'"; executeStatement(true, wizardModel.createUserUsername, wizardModel.createUserPassword, sql, connectionUsername); sql = "create user '?'@'localhost' identified by '?'"; if (-1 != executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword, sql, connectionUsername, connectionPassword)) { wizardModel.workLog.add("Created user " + connectionUsername); } else { // if error occurs stop renderTemplate(DEFAULT_PAGE, null, writer); return; } // grant the roles sql = "GRANT ALL ON `?`.* TO '?'@'localhost'"; int result = executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword, sql, wizardModel.databaseName, connectionUsername); // throw the user back to the main screen if this error occurs if (result < 0) { renderTemplate(DEFAULT_PAGE, null, writer); return; } else { wizardModel.workLog.add("Granted user " + connectionUsername + " all privileges to database " + wizardModel.databaseName); } } else { connectionUsername = wizardModel.currentDatabaseUsername; connectionPassword = wizardModel.currentDatabasePassword; } String finalDatabaseConnectionString = wizardModel.databaseConnection.replace("@DBNAME@", wizardModel.databaseName); // verify that the database connection works if (!verifyConnection(connectionUsername, connectionPassword, finalDatabaseConnectionString)) { // redirect to setup page if we got an error renderTemplate(DEFAULT_PAGE, null, writer); return; } // save the properties for startup purposes runtimeProperties.put("connection.url", finalDatabaseConnectionString); runtimeProperties.put("connection.username", connectionUsername); runtimeProperties.put("connection.password", connectionPassword); runtimeProperties.put("module.allow_web_admin", wizardModel.moduleWebAdmin.toString()); runtimeProperties.put("auto_update_database", wizardModel.autoUpdateDatabase.toString()); runtimeProperties.put(SchedulerConstants.SCHEDULER_USERNAME_PROPERTY, "admin"); runtimeProperties.put(SchedulerConstants.SCHEDULER_PASSWORD_PROPERTY, wizardModel.adminUserPassword); Context.setRuntimeProperties(runtimeProperties); if (wizardModel.createTables) { // use liquibase to create core data + tables try { DatabaseUpdater.executeChangelog(LIQUIBASE_SCHEMA_DATA, null); DatabaseUpdater.executeChangelog(LIQUIBASE_CORE_DATA, null); wizardModel.workLog.add("Created database tables and added core data"); } catch (Exception e) { wizardModel.errors.add(e.getMessage() + " See the error log for more details"); // TODO internationalize this log.warn("Error while trying to create tables and demo data", e); } } // add demo data only if creating tables fresh and user selected the option add demo data if (wizardModel.createTables && wizardModel.addDemoData) { try { DatabaseUpdater.executeChangelog(LIQUIBASE_DEMO_DATA, null); wizardModel.workLog.add("Added demo data"); } catch (Exception e) { wizardModel.errors.add(e.getMessage() + " See the error log for more details"); // TODO internationalize this log.warn("Error while trying to add demo data", e); } } // update the database to the latest version try { DatabaseUpdater.update(); } catch (Exception e) { wizardModel.errors.add(e.getMessage() + " Error while trying to update to the latest database version"); // TODO internationalize this log.warn("Error while trying to update to the latest database version", e); renderTemplate(DEFAULT_PAGE, null, writer); return; } // start spring // after this point, all errors need to also call: contextLoader.closeWebApplicationContext(event.getServletContext()) // logic copied from org.springframework.web.context.ContextLoaderListener ContextLoader contextLoader = new ContextLoader(); contextLoader.initWebApplicationContext(filterConfig.getServletContext()); // start openmrs try { Context.startup(runtimeProperties); } catch (DatabaseUpdateException updateEx) { log.warn("Error while running the database update file", updateEx); wizardModel.errors.add(updateEx.getMessage() + " There was an error while running the database update file: " + updateEx.getMessage()); // TODO internationalize this renderTemplate(DEFAULT_PAGE, null, writer); return; } catch (InputRequiredException inputRequiredEx) { // TODO display a page looping over the required input and ask the user for each. // When done and the user and put in their say, call DatabaseUpdater.update(Map); // with the user's question/answer pairs log .warn("Unable to continue because user input is required for the db updates, but I am not doing anything about that right now"); wizardModel.errors .add("Unable to continue because user input is required for the db updates, but I am not doing anything about that right now"); renderTemplate(DEFAULT_PAGE, null, writer); return; } // TODO catch openmrs errors here and drop the user back out to the setup screen if (!wizardModel.implementationId.equals("")) { try { Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_GLOBAL_PROPERTIES); Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_CONCEPT_SOURCES); Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_SOURCES); ImplementationId implId = new ImplementationId(); implId.setName(wizardModel.implementationIdName); implId.setImplementationId(wizardModel.implementationId); implId.setPassphrase(wizardModel.implementationIdPassPhrase); implId.setDescription(wizardModel.implementationIdDescription); Context.getAdministrationService().setImplementationId(implId); } catch (Throwable t) { wizardModel.errors.add(t.getMessage() + " Implementation ID could not be set."); log.warn("Implementation ID could not be set.", t); renderTemplate(DEFAULT_PAGE, null, writer); Context.shutdown(); WebModuleUtil.shutdownModules(filterConfig.getServletContext()); contextLoader.closeWebApplicationContext(filterConfig.getServletContext()); return; } finally { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_GLOBAL_PROPERTIES); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_CONCEPT_SOURCES); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_SOURCES); } } try { // change the admin user password from "test" to what they input above if (wizardModel.createTables) { Context.authenticate("admin", "test"); Context.getUserService().changePassword("test", wizardModel.adminUserPassword); Context.logout(); } // load modules Listener.loadCoreModules(filterConfig.getServletContext()); // web load modules Listener.performWebStartOfModules(filterConfig.getServletContext()); // start the scheduled tasks SchedulerUtil.startup(runtimeProperties); } catch (Throwable t) { Context.shutdown(); WebModuleUtil.shutdownModules(filterConfig.getServletContext()); contextLoader.closeWebApplicationContext(filterConfig.getServletContext()); wizardModel.errors.add(t.getMessage() + " Unable to complete the startup."); log.warn("Unable to complete the startup.", t); renderTemplate(DEFAULT_PAGE, null, writer); return; } // output properties to the openmrs runtime properties file so that this wizard is not run again FileOutputStream fos = null; try { fos = new FileOutputStream(getRuntimePropertiesFile()); runtimeProperties.store(fos, "Auto generated by OpenMRS initialization wizard"); wizardModel.workLog.add("Saved runtime properties file " + getRuntimePropertiesFile()); // don't need to catch errors here because we tested it at the beginning of the wizard } finally { if (fos != null) { fos.close(); } } // set this so that the wizard isn't run again on next page load initializationComplete = true; // TODO send user to confirmation page with results of wizard, location of runtime props, etc instead? httpResponse.sendRedirect("/" + WebConstants.WEBAPP_NAME); } }
private void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException { String page = httpRequest.getParameter("page"); Map<String, Object> referenceMap = new HashMap<String, Object>(); Writer writer = httpResponse.getWriter(); // clear existing errors wizardModel.errors.clear(); // step one if ("databasesetup.vm".equals(page)) { wizardModel.databaseConnection = httpRequest.getParameter("database_connection"); checkForEmptyValue(wizardModel.databaseConnection, wizardModel.errors, "Database connection string"); // asked the user for their desired database name if ("yes".equals(httpRequest.getParameter("current_openmrs_database"))) { wizardModel.databaseName = httpRequest.getParameter("openmrs_current_database_name"); checkForEmptyValue(wizardModel.databaseName, wizardModel.errors, "Current database name"); wizardModel.hasCurrentOpenmrsDatabase = true; // TODO check to see if this is an active database } else { // mark this wizard as a "to create database" (done at the end) wizardModel.hasCurrentOpenmrsDatabase = false; wizardModel.createTables = true; wizardModel.databaseName = httpRequest.getParameter("openmrs_new_database_name"); checkForEmptyValue(wizardModel.databaseName, wizardModel.errors, "New database name"); // TODO create database now to check if its possible? wizardModel.createDatabaseUsername = httpRequest.getParameter("create_database_username"); checkForEmptyValue(wizardModel.createDatabaseUsername, wizardModel.errors, "A user that has 'CREATE DATABASE' privileges"); wizardModel.createDatabasePassword = httpRequest.getParameter("create_database_password"); checkForEmptyValue(wizardModel.createDatabasePassword, wizardModel.errors, "Password for user with 'CREATE DATABASE' privileges"); } if (wizardModel.errors.isEmpty()) { page = "databasetablesanduser.vm"; } renderTemplate(page, referenceMap, writer); } // step two else if ("databasetablesanduser.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { renderTemplate("databasesetup.vm", referenceMap, writer); return; } if (wizardModel.hasCurrentOpenmrsDatabase) { wizardModel.createTables = "yes".equals(httpRequest.getParameter("create_tables")); } wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data")); if ("yes".equals(httpRequest.getParameter("current_database_user"))) { wizardModel.currentDatabaseUsername = httpRequest.getParameter("current_database_username"); checkForEmptyValue(wizardModel.currentDatabaseUsername, wizardModel.errors, "Curent user account"); wizardModel.currentDatabasePassword = httpRequest.getParameter("current_database_password"); checkForEmptyValue(wizardModel.currentDatabasePassword, wizardModel.errors, "Current user account password"); wizardModel.hasCurrentDatabaseUser = true; wizardModel.createDatabaseUser = false; } else { wizardModel.hasCurrentDatabaseUser = false; wizardModel.createDatabaseUser = true; // asked for the root mysql username/password wizardModel.createUserUsername = httpRequest.getParameter("create_user_username"); checkForEmptyValue(wizardModel.createUserUsername, wizardModel.errors, "A user that has 'CREATE USER' privileges"); wizardModel.createUserPassword = httpRequest.getParameter("create_user_password"); checkForEmptyValue(wizardModel.createUserPassword, wizardModel.errors, "Password for user that has 'CREATE USER' privileges"); } if (wizardModel.errors.isEmpty()) { // go to next page page = "otherruntimeproperties.vm"; } renderTemplate(page, referenceMap, writer); } // step three else if ("otherruntimeproperties.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { renderTemplate("databasetablesanduser.vm", referenceMap, writer); return; } wizardModel.moduleWebAdmin = "yes".equals(httpRequest.getParameter("module_web_admin")); wizardModel.autoUpdateDatabase = "yes".equals(httpRequest.getParameter("auto_update_database")); if (wizardModel.createTables) { // go to next page if they are creating tables page = "adminusersetup.vm"; } else { // skip a page page = "implementationidsetup.vm"; } renderTemplate(page, referenceMap, writer); } // optional step four else if ("adminusersetup.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { renderTemplate("otherruntimeproperties.vm", referenceMap, writer); return; } wizardModel.adminUserPassword = httpRequest.getParameter("new_admin_password"); String adminUserConfirm = httpRequest.getParameter("new_admin_password_confirm"); // throw back to admin user if passwords don't match if (!wizardModel.adminUserPassword.equals(adminUserConfirm)) { wizardModel.errors.add("Admin passwords don't match"); renderTemplate("adminusersetup.vm", referenceMap, writer); return; } // throw back if the user didn't put in a password if (wizardModel.adminUserPassword.equals("")) { wizardModel.errors.add("An admin password is required"); renderTemplate("adminusersetup.vm", referenceMap, writer); return; } try { OpenmrsUtil.validatePassword("admin", wizardModel.adminUserPassword, "admin"); } catch (PasswordException p) { wizardModel.errors.add("The password is not long enough, does not contain both uppercase characters and a number, or matches the username."); renderTemplate("adminusersetup.vm", referenceMap, writer); return; } if (wizardModel.errors.isEmpty()) { // go to next page page = "implementationidsetup.vm"; } renderTemplate(page, referenceMap, writer); } // optional step five else if ("implementationidsetup.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { if (wizardModel.createTables) renderTemplate("adminusersetup.vm", referenceMap, writer); else renderTemplate("otherruntimeproperties.vm", referenceMap, writer); return; } wizardModel.implementationIdName = httpRequest.getParameter("implementation_name"); wizardModel.implementationId = httpRequest.getParameter("implementation_id"); wizardModel.implementationIdPassPhrase = httpRequest.getParameter("pass_phrase"); wizardModel.implementationIdDescription = httpRequest.getParameter("description"); // throw back if the user-specified ID is invalid (contains ^ or |). if (wizardModel.implementationId.indexOf('^') != -1 || wizardModel.implementationId.indexOf('|') != -1) { wizardModel.errors.add("Implementation ID cannot contain '^' or '|'"); renderTemplate("implementationidsetup.vm", referenceMap, writer); return; } if (wizardModel.errors.isEmpty()) { // go to next page page = "wizardcomplete.vm"; } renderTemplate(page, referenceMap, writer); } else if ("wizardcomplete.vm".equals(page)) { if ("Back".equals(httpRequest.getParameter("back"))) { renderTemplate("implementationidsetup.vm", referenceMap, writer); return; } Properties runtimeProperties = new Properties(); String connectionUsername; String connectionPassword; if (!wizardModel.hasCurrentOpenmrsDatabase) { // connect via jdbc and create a database String sql = "create database `?` default character set utf8"; int result = executeStatement(false, wizardModel.createDatabaseUsername, wizardModel.createDatabasePassword, sql, wizardModel.databaseName); // throw the user back to the main screen if this error occurs if (result < 0) { renderTemplate(DEFAULT_PAGE, null, writer); return; } else { wizardModel.workLog.add("Created database " + wizardModel.databaseName); } } if (wizardModel.createDatabaseUser) { connectionUsername = wizardModel.databaseName + "_user"; if (connectionUsername.length() > 16) connectionUsername = wizardModel.databaseName.substring(0, 11) + "_user"; // trim off enough to leave space for _user at the end connectionPassword = ""; // generate random password from this subset of alphabet // intentionally left out these characters: ufsb$() to prevent certain words forming randomly String chars = "acdeghijklmnopqrtvwxyzACDEGHIJKLMNOPQRTVWXYZ0123456789.|~@#^&"; Random r = new Random(); for (int x = 0; x < 12; x++) { connectionPassword += chars.charAt(r.nextInt(chars.length())); } // connect via jdbc with root user and create an openmrs user String sql = "drop user '?'@'localhost'"; executeStatement(true, wizardModel.createUserUsername, wizardModel.createUserPassword, sql, connectionUsername); sql = "create user '?'@'localhost' identified by '?'"; if (-1 != executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword, sql, connectionUsername, connectionPassword)) { wizardModel.workLog.add("Created user " + connectionUsername); } else { // if error occurs stop renderTemplate(DEFAULT_PAGE, null, writer); return; } // grant the roles sql = "GRANT ALL ON `?`.* TO '?'@'localhost'"; int result = executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword, sql, wizardModel.databaseName, connectionUsername); // throw the user back to the main screen if this error occurs if (result < 0) { renderTemplate(DEFAULT_PAGE, null, writer); return; } else { wizardModel.workLog.add("Granted user " + connectionUsername + " all privileges to database " + wizardModel.databaseName); } } else { connectionUsername = wizardModel.currentDatabaseUsername; connectionPassword = wizardModel.currentDatabasePassword; } String finalDatabaseConnectionString = wizardModel.databaseConnection.replace("@DBNAME@", wizardModel.databaseName); // verify that the database connection works if (!verifyConnection(connectionUsername, connectionPassword, finalDatabaseConnectionString)) { // redirect to setup page if we got an error renderTemplate(DEFAULT_PAGE, null, writer); return; } // save the properties for startup purposes runtimeProperties.put("connection.url", finalDatabaseConnectionString); runtimeProperties.put("connection.username", connectionUsername); runtimeProperties.put("connection.password", connectionPassword); runtimeProperties.put("module.allow_web_admin", wizardModel.moduleWebAdmin.toString()); runtimeProperties.put("auto_update_database", wizardModel.autoUpdateDatabase.toString()); runtimeProperties.put(SchedulerConstants.SCHEDULER_USERNAME_PROPERTY, "admin"); runtimeProperties.put(SchedulerConstants.SCHEDULER_PASSWORD_PROPERTY, wizardModel.adminUserPassword); Context.setRuntimeProperties(runtimeProperties); if (wizardModel.createTables) { // use liquibase to create core data + tables try { DatabaseUpdater.executeChangelog(LIQUIBASE_SCHEMA_DATA, null); DatabaseUpdater.executeChangelog(LIQUIBASE_CORE_DATA, null); wizardModel.workLog.add("Created database tables and added core data"); } catch (Exception e) { wizardModel.errors.add(e.getMessage() + " See the error log for more details"); // TODO internationalize this log.warn("Error while trying to create tables and demo data", e); } } // add demo data only if creating tables fresh and user selected the option add demo data if (wizardModel.createTables && wizardModel.addDemoData) { try { DatabaseUpdater.executeChangelog(LIQUIBASE_DEMO_DATA, null); wizardModel.workLog.add("Added demo data"); } catch (Exception e) { wizardModel.errors.add(e.getMessage() + " See the error log for more details"); // TODO internationalize this log.warn("Error while trying to add demo data", e); } } // update the database to the latest version try { DatabaseUpdater.update(); } catch (Exception e) { wizardModel.errors.add(e.getMessage() + " Error while trying to update to the latest database version"); // TODO internationalize this log.warn("Error while trying to update to the latest database version", e); renderTemplate(DEFAULT_PAGE, null, writer); return; } // start spring // after this point, all errors need to also call: contextLoader.closeWebApplicationContext(event.getServletContext()) // logic copied from org.springframework.web.context.ContextLoaderListener ContextLoader contextLoader = new ContextLoader(); contextLoader.initWebApplicationContext(filterConfig.getServletContext()); // start openmrs try { Context.openSession(); Context.startup(runtimeProperties); } catch (DatabaseUpdateException updateEx) { log.warn("Error while running the database update file", updateEx); wizardModel.errors.add(updateEx.getMessage() + " There was an error while running the database update file: " + updateEx.getMessage()); // TODO internationalize this renderTemplate(DEFAULT_PAGE, null, writer); return; } catch (InputRequiredException inputRequiredEx) { // TODO display a page looping over the required input and ask the user for each. // When done and the user and put in their say, call DatabaseUpdater.update(Map); // with the user's question/answer pairs log .warn("Unable to continue because user input is required for the db updates, but I am not doing anything about that right now"); wizardModel.errors .add("Unable to continue because user input is required for the db updates, but I am not doing anything about that right now"); renderTemplate(DEFAULT_PAGE, null, writer); return; } // TODO catch openmrs errors here and drop the user back out to the setup screen if (!wizardModel.implementationId.equals("")) { try { Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_GLOBAL_PROPERTIES); Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_CONCEPT_SOURCES); Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_SOURCES); ImplementationId implId = new ImplementationId(); implId.setName(wizardModel.implementationIdName); implId.setImplementationId(wizardModel.implementationId); implId.setPassphrase(wizardModel.implementationIdPassPhrase); implId.setDescription(wizardModel.implementationIdDescription); Context.getAdministrationService().setImplementationId(implId); } catch (Throwable t) { wizardModel.errors.add(t.getMessage() + " Implementation ID could not be set."); log.warn("Implementation ID could not be set.", t); renderTemplate(DEFAULT_PAGE, null, writer); Context.shutdown(); WebModuleUtil.shutdownModules(filterConfig.getServletContext()); contextLoader.closeWebApplicationContext(filterConfig.getServletContext()); return; } finally { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_GLOBAL_PROPERTIES); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_CONCEPT_SOURCES); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_SOURCES); } } try { // change the admin user password from "test" to what they input above if (wizardModel.createTables) { Context.authenticate("admin", "test"); Context.getUserService().changePassword("test", wizardModel.adminUserPassword); Context.logout(); } // load modules Listener.loadCoreModules(filterConfig.getServletContext()); // web load modules Listener.performWebStartOfModules(filterConfig.getServletContext()); // start the scheduled tasks SchedulerUtil.startup(runtimeProperties); } catch (Throwable t) { Context.shutdown(); WebModuleUtil.shutdownModules(filterConfig.getServletContext()); contextLoader.closeWebApplicationContext(filterConfig.getServletContext()); wizardModel.errors.add(t.getMessage() + " Unable to complete the startup."); log.warn("Unable to complete the startup.", t); renderTemplate(DEFAULT_PAGE, null, writer); return; } // output properties to the openmrs runtime properties file so that this wizard is not run again FileOutputStream fos = null; try { fos = new FileOutputStream(getRuntimePropertiesFile()); runtimeProperties.store(fos, "Auto generated by OpenMRS initialization wizard"); wizardModel.workLog.add("Saved runtime properties file " + getRuntimePropertiesFile()); // don't need to catch errors here because we tested it at the beginning of the wizard } finally { if (fos != null) { fos.close(); } } // set this so that the wizard isn't run again on next page load initializationComplete = true; Context.closeSession(); // TODO send user to confirmation page with results of wizard, location of runtime props, etc instead? httpResponse.sendRedirect("/" + WebConstants.WEBAPP_NAME); } }
diff --git a/src/com/axelby/podax/ui/AddSubscriptionFragment.java b/src/com/axelby/podax/ui/AddSubscriptionFragment.java index 2ac3591..38cd7e2 100644 --- a/src/com/axelby/podax/ui/AddSubscriptionFragment.java +++ b/src/com/axelby/podax/ui/AddSubscriptionFragment.java @@ -1,305 +1,305 @@ package com.axelby.podax.ui; import java.io.File; import java.io.FileFilter; import java.io.IOException; import org.xml.sax.SAXException; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.text.InputType; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.app.SherlockListFragment; import com.axelby.podax.GoogleReaderImporter; import com.axelby.podax.Helper; import com.axelby.podax.OPMLImporter; import com.axelby.podax.R; import com.axelby.podax.SubscriptionProvider; import com.axelby.podax.UpdateService; public class AddSubscriptionFragment extends SherlockListFragment { private AccountManager _accountManager; private Account[] _gpodderAccounts; private Account[] _googleAccounts = { }; private Account _chosenAccount; private final int ADD_RSS = 0; private final int ADD_OPML = 1; private final int ADD_GPODDER = 2; private final int GOOGLE_ACCOUNT_HEADER = 3; private final int GOOGLE_ACCOUNT_START = 4; private AccountManagerCallback<Bundle> _accountCallback = new AccountManagerCallback<Bundle>() { public void run(AccountManagerFuture<Bundle> future) { Bundle authTokenBundle = null; try { authTokenBundle = future.getResult(); if (authTokenBundle == null) return; if(authTokenBundle.containsKey(AccountManager.KEY_INTENT)) { // User input required Intent intent = (Intent)authTokenBundle.get(AccountManager.KEY_INTENT); // clear the new task flag int flags = intent.getFlags(); flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK; intent.setFlags(flags); startActivityForResult(intent, 1); return; } String authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); new GoogleReaderImporter(getActivity()).doImport(authToken); } catch (OperationCanceledException e) { Log.e("Podax", "Operation Canceled", e); } catch (IOException e) { Log.e("Podax", "IOException", e); } catch (AuthenticatorException e) { Log.e("Podax", "Authentication Failed", e); } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.subscription_list, null, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); _accountManager = AccountManager.get(getActivity()); _gpodderAccounts = _accountManager.getAccountsByType("com.axelby.gpodder.account"); _accountManager.getAccountsByTypeAndFeatures("com.google", new String[] { "service_reader" }, new AccountManagerCallback<Account[]>() { public void run(AccountManagerFuture<Account[]> future) { try { _googleAccounts = future.getResult(); } catch (OperationCanceledException e) { Log.e("Podax", "Operation Canceled", e); } catch (IOException e) { Log.e("Podax", "IOException", e); } catch (AuthenticatorException e) { // no authenticator registered } finally { setListAdapter(new ImportSubscriptionAdapter()); } } }, null); } @Override public void onListItemClick(ListView l, View v, int position, long id) { if (position == ADD_RSS) { AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setTitle("Podcast URL"); alert.setMessage("Type the URL of the podcast RSS"); final EditText input = new EditText(getActivity()); //input.setText("http://blog.axelby.com/podcast.xml"); input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI); alert.setView(input); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String subscriptionUrl = input.getText().toString(); if (!subscriptionUrl.contains("://")) subscriptionUrl = "http://" + subscriptionUrl; ContentValues values = new ContentValues(); values.put(SubscriptionProvider.COLUMN_URL, subscriptionUrl); values.put(SubscriptionProvider.COLUMN_TITLE, subscriptionUrl); Uri subscriptionUri = getActivity().getContentResolver().insert(SubscriptionProvider.URI, values); UpdateService.updateSubscription(getActivity(), subscriptionUri); } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // do nothing } }); alert.show(); return; } if (position == ADD_OPML) { FileFilter fileFilter = new FileFilter() { public boolean accept(File pathname) { return pathname.getName().equals("podcasts.opml"); } }; File externalStorageDir = Environment.getExternalStorageDirectory(); File[] opmlFiles = externalStorageDir.listFiles(fileFilter); - if (opmlFiles.length == 0) { + if (opmlFiles!= null && opmlFiles.length == 0) { String message = "The OPML file must be at " + externalStorageDir.getAbsolutePath() + "/podcasts.opml."; Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); return; } try { int newSubscriptions = OPMLImporter.read(getActivity(), opmlFiles[0]); String message = "Found " + newSubscriptions + " subscriptions."; Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show(); getActivity().finish(); getActivity().startActivity(MainActivity.getSubscriptionIntent(getActivity())); } catch (IOException e) { String message = "There was an error while reading the OPML file."; Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); } catch (SAXException e) { String message = "The podcasts.opml file is not valid OPML."; Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); } return; } if (position == ADD_GPODDER) { if (_gpodderAccounts.length > 0) { return; } else if (!Helper.isGPodderInstalled(getActivity())) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.axelby.gpodder")); intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); startActivity(intent); } else { Intent intent = new Intent(); intent.setClassName("com.axelby.gpodder", "com.axelby.gpodder.AuthenticatorActivity"); startActivity(intent); } } if (position >= GOOGLE_ACCOUNT_START) { _chosenAccount = _googleAccounts[position - GOOGLE_ACCOUNT_START]; getAuthToken(); return; } super.onListItemClick(l, v, position, id); } public class ImportSubscriptionAdapter extends BaseAdapter { LayoutInflater _inflater; public ImportSubscriptionAdapter() { _inflater = (LayoutInflater)getActivity().getSystemService(Activity.LAYOUT_INFLATER_SERVICE); } public int getCount() { return _googleAccounts.length == 0 ? GOOGLE_ACCOUNT_START - 1: _googleAccounts.length + GOOGLE_ACCOUNT_START; } public Object getItem(int position) { if (position < GOOGLE_ACCOUNT_START) return null; return _googleAccounts[position - GOOGLE_ACCOUNT_START]; } public long getItemId(int position) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { if (position == ADD_RSS) { TextView view = (TextView) _inflater.inflate(R.layout.list_item, null); view.setText(R.string.add_rss_feed); return view; } if (position == ADD_OPML) { TextView view = (TextView) _inflater.inflate(R.layout.list_item, null); view.setText(R.string.add_from_opml_file); return view; } if (position == ADD_GPODDER) { View view = _inflater.inflate(R.layout.subscription_list_item, null); TextView text = (TextView)view.findViewById(R.id.text); ImageView thumbnail = (ImageView)view.findViewById(R.id.thumbnail); thumbnail.setImageResource(R.drawable.mygpo); if (_gpodderAccounts.length == 0) text.setText("Link a GPodder account"); else text.setText("Linked to " + _gpodderAccounts[0].name); return view; } if (position == GOOGLE_ACCOUNT_HEADER) { TextView view = new TextView(getActivity()); view.setTextAppearance(getActivity(), android.R.style.TextAppearance_Medium); view.setBackgroundDrawable(getResources().getDrawable(R.drawable.back)); view.setText("Google Reader Accounts"); return view; } TextView view = (TextView) _inflater.inflate(R.layout.list_item, null); view.setText(_googleAccounts[position - GOOGLE_ACCOUNT_START].name); return view; } public boolean areAllItemsEnabled() { return false; } public boolean isEnabled(int position) { return position != GOOGLE_ACCOUNT_HEADER; } } @SuppressWarnings("deprecation") @SuppressLint("NewApi") private void getAuthToken() { if (_chosenAccount == null) return; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { _accountManager.getAuthToken(_chosenAccount, "reader", null, true, _accountCallback, null); } else { _accountManager.getAuthToken(_chosenAccount, "reader", true, _accountCallback, null); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { if (resultCode == Activity.RESULT_OK && data == null) getAuthToken(); } } }
true
true
public void onListItemClick(ListView l, View v, int position, long id) { if (position == ADD_RSS) { AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setTitle("Podcast URL"); alert.setMessage("Type the URL of the podcast RSS"); final EditText input = new EditText(getActivity()); //input.setText("http://blog.axelby.com/podcast.xml"); input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI); alert.setView(input); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String subscriptionUrl = input.getText().toString(); if (!subscriptionUrl.contains("://")) subscriptionUrl = "http://" + subscriptionUrl; ContentValues values = new ContentValues(); values.put(SubscriptionProvider.COLUMN_URL, subscriptionUrl); values.put(SubscriptionProvider.COLUMN_TITLE, subscriptionUrl); Uri subscriptionUri = getActivity().getContentResolver().insert(SubscriptionProvider.URI, values); UpdateService.updateSubscription(getActivity(), subscriptionUri); } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // do nothing } }); alert.show(); return; } if (position == ADD_OPML) { FileFilter fileFilter = new FileFilter() { public boolean accept(File pathname) { return pathname.getName().equals("podcasts.opml"); } }; File externalStorageDir = Environment.getExternalStorageDirectory(); File[] opmlFiles = externalStorageDir.listFiles(fileFilter); if (opmlFiles.length == 0) { String message = "The OPML file must be at " + externalStorageDir.getAbsolutePath() + "/podcasts.opml."; Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); return; } try { int newSubscriptions = OPMLImporter.read(getActivity(), opmlFiles[0]); String message = "Found " + newSubscriptions + " subscriptions."; Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show(); getActivity().finish(); getActivity().startActivity(MainActivity.getSubscriptionIntent(getActivity())); } catch (IOException e) { String message = "There was an error while reading the OPML file."; Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); } catch (SAXException e) { String message = "The podcasts.opml file is not valid OPML."; Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); } return; } if (position == ADD_GPODDER) { if (_gpodderAccounts.length > 0) { return; } else if (!Helper.isGPodderInstalled(getActivity())) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.axelby.gpodder")); intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); startActivity(intent); } else { Intent intent = new Intent(); intent.setClassName("com.axelby.gpodder", "com.axelby.gpodder.AuthenticatorActivity"); startActivity(intent); } } if (position >= GOOGLE_ACCOUNT_START) { _chosenAccount = _googleAccounts[position - GOOGLE_ACCOUNT_START]; getAuthToken(); return; } super.onListItemClick(l, v, position, id); }
public void onListItemClick(ListView l, View v, int position, long id) { if (position == ADD_RSS) { AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setTitle("Podcast URL"); alert.setMessage("Type the URL of the podcast RSS"); final EditText input = new EditText(getActivity()); //input.setText("http://blog.axelby.com/podcast.xml"); input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI); alert.setView(input); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String subscriptionUrl = input.getText().toString(); if (!subscriptionUrl.contains("://")) subscriptionUrl = "http://" + subscriptionUrl; ContentValues values = new ContentValues(); values.put(SubscriptionProvider.COLUMN_URL, subscriptionUrl); values.put(SubscriptionProvider.COLUMN_TITLE, subscriptionUrl); Uri subscriptionUri = getActivity().getContentResolver().insert(SubscriptionProvider.URI, values); UpdateService.updateSubscription(getActivity(), subscriptionUri); } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // do nothing } }); alert.show(); return; } if (position == ADD_OPML) { FileFilter fileFilter = new FileFilter() { public boolean accept(File pathname) { return pathname.getName().equals("podcasts.opml"); } }; File externalStorageDir = Environment.getExternalStorageDirectory(); File[] opmlFiles = externalStorageDir.listFiles(fileFilter); if (opmlFiles!= null && opmlFiles.length == 0) { String message = "The OPML file must be at " + externalStorageDir.getAbsolutePath() + "/podcasts.opml."; Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); return; } try { int newSubscriptions = OPMLImporter.read(getActivity(), opmlFiles[0]); String message = "Found " + newSubscriptions + " subscriptions."; Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show(); getActivity().finish(); getActivity().startActivity(MainActivity.getSubscriptionIntent(getActivity())); } catch (IOException e) { String message = "There was an error while reading the OPML file."; Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); } catch (SAXException e) { String message = "The podcasts.opml file is not valid OPML."; Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); } return; } if (position == ADD_GPODDER) { if (_gpodderAccounts.length > 0) { return; } else if (!Helper.isGPodderInstalled(getActivity())) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.axelby.gpodder")); intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); startActivity(intent); } else { Intent intent = new Intent(); intent.setClassName("com.axelby.gpodder", "com.axelby.gpodder.AuthenticatorActivity"); startActivity(intent); } } if (position >= GOOGLE_ACCOUNT_START) { _chosenAccount = _googleAccounts[position - GOOGLE_ACCOUNT_START]; getAuthToken(); return; } super.onListItemClick(l, v, position, id); }
diff --git a/src/xmlvm/org/xmlvm/Main.java b/src/xmlvm/org/xmlvm/Main.java index 9dc95f3c..cd37325f 100755 --- a/src/xmlvm/org/xmlvm/Main.java +++ b/src/xmlvm/org/xmlvm/Main.java @@ -1,76 +1,81 @@ /* * Copyright (c) 2004-2009 XMLVM --- An XML-based Programming Language * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 675 Mass * Ave, Cambridge, MA 02139, USA. * * For more information, visit the XMLVM Home Page at http://www.xmlvm.org */ package org.xmlvm; import org.xmlvm.main.Arguments; import org.xmlvm.proc.XmlvmProcessor; import org.xmlvm.util.Timer; /** * This is a new starting point of the suggested refactoring of the old * Main.java. */ public class Main { /** * XMLVM entry point. */ public static void main(String[] args) { // Initialize arguments. Arguments arguments = new Arguments(args); // Sets whether log messages should be shown or not. Log.setLevel(arguments.option_debug()); // Enable a timer if wanted. Timer timer = null; if (arguments.option_enable_timer()) { (timer = new Timer("XMLVM total execution time")).start(); } // Instantiate the processor. XmlvmProcessor processor = new XmlvmProcessor(arguments); - // 1) Processing. - if (processor.process()) { - Log.debug("Processing finished successfully."); - // 2) Writing files. - if (processor.writeOutputFiles()) { - Log.debug("Files written successfully."); - // 3) Post-Processing. - if (processor.postProcess()) { - Log.debug("Post-Processing successful."); + try { + // 1) Processing. + if (processor.process()) { + Log.debug("Processing finished successfully."); + // 2) Writing files. + if (processor.writeOutputFiles()) { + Log.debug("Files written successfully."); + // 3) Post-Processing. + if (processor.postProcess()) { + Log.debug("Post-Processing successful."); + } else { + Log.error("Something went wrong during post-processing."); + } } else { - Log.error("Something went wrong during post-processing."); + Log.error("Something went wrong while writing files."); } } else { - Log.error("Something went wrong while writing files."); + Log.error("Something went wrong during processing."); } - } else { - Log.error("Something went wrong during processing."); + } catch (OutOfMemoryError e) { + Log.error("Oh no, XMLVM needs more memory. Try running with -Xmx1G."); + return; } // If timer was configured, print result. if (timer != null) { Log.debug(timer.stop().toString()); } } }
false
true
public static void main(String[] args) { // Initialize arguments. Arguments arguments = new Arguments(args); // Sets whether log messages should be shown or not. Log.setLevel(arguments.option_debug()); // Enable a timer if wanted. Timer timer = null; if (arguments.option_enable_timer()) { (timer = new Timer("XMLVM total execution time")).start(); } // Instantiate the processor. XmlvmProcessor processor = new XmlvmProcessor(arguments); // 1) Processing. if (processor.process()) { Log.debug("Processing finished successfully."); // 2) Writing files. if (processor.writeOutputFiles()) { Log.debug("Files written successfully."); // 3) Post-Processing. if (processor.postProcess()) { Log.debug("Post-Processing successful."); } else { Log.error("Something went wrong during post-processing."); } } else { Log.error("Something went wrong while writing files."); } } else { Log.error("Something went wrong during processing."); } // If timer was configured, print result. if (timer != null) { Log.debug(timer.stop().toString()); } }
public static void main(String[] args) { // Initialize arguments. Arguments arguments = new Arguments(args); // Sets whether log messages should be shown or not. Log.setLevel(arguments.option_debug()); // Enable a timer if wanted. Timer timer = null; if (arguments.option_enable_timer()) { (timer = new Timer("XMLVM total execution time")).start(); } // Instantiate the processor. XmlvmProcessor processor = new XmlvmProcessor(arguments); try { // 1) Processing. if (processor.process()) { Log.debug("Processing finished successfully."); // 2) Writing files. if (processor.writeOutputFiles()) { Log.debug("Files written successfully."); // 3) Post-Processing. if (processor.postProcess()) { Log.debug("Post-Processing successful."); } else { Log.error("Something went wrong during post-processing."); } } else { Log.error("Something went wrong while writing files."); } } else { Log.error("Something went wrong during processing."); } } catch (OutOfMemoryError e) { Log.error("Oh no, XMLVM needs more memory. Try running with -Xmx1G."); return; } // If timer was configured, print result. if (timer != null) { Log.debug(timer.stop().toString()); } }
diff --git a/app/controllers/UserApp.java b/app/controllers/UserApp.java index f06e226a..1509251f 100644 --- a/app/controllers/UserApp.java +++ b/app/controllers/UserApp.java @@ -1,642 +1,642 @@ package controllers; import com.avaje.ebean.ExpressionList; import models.*; import models.enumeration.Operation; import org.apache.commons.lang.StringUtils; import org.apache.shiro.crypto.RandomNumberGenerator; import org.apache.shiro.crypto.SecureRandomNumberGenerator; import org.apache.shiro.crypto.hash.Sha256Hash; import org.apache.shiro.util.ByteSource; import play.Configuration; import play.Logger; import play.data.Form; import play.mvc.*; import play.mvc.Http.Cookie; import utils.AccessControl; import utils.Constants; import utils.JodaDateUtil; import utils.ReservedWordsValidator; import utils.ErrorViews; import views.html.login; import views.html.user.*; import org.codehaus.jackson.node.ObjectNode; import play.libs.Json; import java.util.*; import static play.data.Form.form; import static play.libs.Json.toJson; public class UserApp extends Controller { public static final String SESSION_USERID = "userId"; public static final String SESSION_LOGINID = "loginId"; public static final String SESSION_USERNAME = "userName"; public static final String TOKEN = "nforge.token"; public static final int MAX_AGE = 30*24*60*60; public static final String DEFAULT_AVATAR_URL = "/assets/images/default-avatar-128.png"; public static final int MAX_FETCH_USERS = 1000; private static final int HASH_ITERATIONS = 1024; public static final int DAYS_AGO = 7; public static final int UNDEFINED = 0; public static final String DAYS_AGO_COOKIE = "daysAgo"; public static final String DEFAULT_GROUP = "own"; public static final String DEFAULT_SELECTED_TAB = "projects"; /** * ajax 를 이용한 사용자 검색 * 요청 헤더의 accept 파라미터에 application/json 값이 없으면 406 응답 * 응답에 포함되는 데이터 수는 MAX_FETCH_USERS 로 제한된다 * 입력 파라미터 query 가 부분매칭 되는 loginId 목록을 json 형태로 응답 * * @param query 검색어 * @return */ public static Result users(String query) { if (!request().accepts("application/json")) { return status(Http.Status.NOT_ACCEPTABLE); } ExpressionList<User> el = User.find.select("loginId").where().contains("loginId", query); int total = el.findRowCount(); if (total > MAX_FETCH_USERS) { el.setMaxRows(MAX_FETCH_USERS); response().setHeader("Content-Range", "items " + MAX_FETCH_USERS + "/" + total); } List<String> loginIds = new ArrayList<>(); for (User user: el.findList()) { loginIds.add(user.loginId); } return ok(toJson(loginIds)); } /** * 로그인 폼으로 이동 * * @return */ public static Result loginForm() { return ok(login.render("title.login", form(User.class))); } /** * 로그아웃 * 로그인 유지 기능 해제 * 메인으로 이동 * * @return */ public static Result logout() { processLogout(); flash(Constants.SUCCESS, "user.logout.success"); return redirect(routes.Application.index()); } /** * 로그인 처리 * 시스템 설정에서 가입승인 기능이 활성화 되어 있고 사용자 상태가 잠금상태(미승인?)라면 계정이 잠겼다는 메시지를 노출하고 로그인 폼으로 돌아감 * 시스템 설정에서 가입승인 기능이 활성화 되어 있지 않다면, 사용자 상태가 잠금상태라도 로그인이 가능하다 (스펙확인 필요) * 요청의 정보로 사용자 인증에 성공하면 로그인쿠키를 생성하고 로그인유지하기가 선택되었다면, 로그인유지를 위한 쿠키를 별도로 생성한다 * 인증에 실패하면 관련된 메시지를 노출하고 로그인 폼으로 돌아간다 * * @return */ public static Result login() { Form<User> userForm = form(User.class).bindFromRequest(); if(userForm.hasErrors()) { return badRequest(login.render("title.login", userForm)); } User sourceUser = form(User.class).bindFromRequest().get(); if (isUseSignUpConfirm()) { if (User.findByLoginId(sourceUser.loginId).isLocked == true ) { flash(Constants.WARNING, "user.locked"); return redirect(routes.UserApp.loginForm()); } } User authenticate = authenticateWithPlainPassword(sourceUser.loginId, sourceUser.password); if (authenticate != null) { addUserInfoToSession(authenticate); if (sourceUser.rememberMe) { setupRememberMe(authenticate); } return redirect(routes.Application.index()); } flash(Constants.WARNING, "user.login.failed"); return redirect(routes.UserApp.loginForm()); } /** * loginId 와 hash 값을 이용해서 사용자 인증. * 인증에 성공하면 DB 에서 조회된 사용자 정보를 리턴 * 인증에 실패하면 null 리턴 * * @param loginId 로그인ID * @param password hash된 비밀번호 * @return */ public static User authenticateWithHashedPassword(String loginId, String password) { User user = User.findByLoginId(loginId); return authenticate(user, password); } /** * loginId 와 plain password 를 이용해서 사용자 인증 * 인증에 성공하면 DB 에서 조회된 사용자 정보를 리턴 * 인증에 실패하면 null 리턴 * * @param loginId 로그인ID * @param password 입력받은 비밀번호 * @return */ public static User authenticateWithPlainPassword(String loginId, String password) { User user = User.findByLoginId(loginId); return authenticate(user, hashedPassword(password, user.passwordSalt)); } /** * 로그인 유지기능 사용 여부 * 로그인 유지 기능이 사용중이면 로그인쿠키를 생성하고 true 를 리턴 * 사용중이지 않으면 false 리턴 * * @return 로그인 유지기능 사용 여부 */ public static boolean isRememberMe() { // Remember Me Cookie cookie = request().cookies().get(TOKEN); if (cookie != null) { String[] subject = cookie.value().split(":"); Logger.debug(cookie.value()); if(subject.length < 2) return false; User user = authenticateWithHashedPassword(subject[0], subject[1]); if (user != null) { addUserInfoToSession(user); } return true; } return false; } /** * 사용자 가입 화면 이동 * * @return */ public static Result signupForm() { return ok(signup.render("title.signup", form(User.class))); } /** * 사용자 가입 처리 * 입력된 데이터 유효성 검증에 실패하면 bad request 응답 * 사용자 정보를 저장, 로그인 쿠기 생성 후 메인 페이지로 이동 * 시스템 설정에서 가입승인 기능이 활성화되어 있다면 사용자의 계정 상태를 잠금으로 설정하여 저장, 로그인 쿠키 생성 안됨 * * @return */ public static Result newUser() { Form<User> newUserForm = form(User.class).bindFromRequest(); validate(newUserForm); if (newUserForm.hasErrors()) { return badRequest(signup.render("title.signup", newUserForm)); } else { User user = createNewUser(newUserForm.get()); User.create(user); if (user.isLocked) { flash(Constants.INFO, "user.signup.requested"); } else { addUserInfoToSession(user); } return redirect(routes.Application.index()); } } /** * 사용자 비밀번호 변경 * 비밀번호 변경에 성공하면 로그인 화면으로 이동 * 비밀번호 변경에 실패하면 수정화면으로 돌아간다 * * @return */ public static Result resetUserPassword() { Form<User> userForm = form(User.class).bindFromRequest(); if(userForm.hasErrors()) { return badRequest(ErrorViews.BadRequest.render("error.badrequest")); } User currentUser = currentUser(); User user = userForm.get(); if(!isValidPassword(currentUser, user.oldPassword)) { Form<User> currentUserForm = new Form<>(User.class); currentUserForm = currentUserForm.fill(currentUser); flash(Constants.WARNING, "user.wrongPassword.alert"); return badRequest(edit.render(currentUserForm, currentUser)); } resetPassword(currentUser, user.password); //go to login page processLogout(); flash(Constants.WARNING, "user.loginWithNewPassword"); return redirect(routes.UserApp.loginForm()); } /** * 비밀번호 검증 * 사용자 객체의 hash 된 비밀번호 값과 입력 받은 비밀번호의 hash 값이 같은지 검사한다 * * @param currentUser 사용자 객체 * @param password 입력받은 비밀번호 * @return */ public static boolean isValidPassword(User currentUser, String password) { String hashedOldPassword = hashedPassword(password, currentUser.passwordSalt); return currentUser.password.equals(hashedOldPassword); } /** * 신규 비밀번호의 hash 값을 구하여 설정 후 저장한다 * * @param user 사용자객체 * @param newPassword 신규비밀번호 */ public static void resetPassword(User user, String newPassword) { user.password = hashedPassword(newPassword, user.passwordSalt); user.save(); } /** * 세션에 저장된 정보를 이용해서 사용자 객체를 생성한다 * 세션에 저장된 정보가 없다면 anonymous 객체가 리턴된다 * * @return 세션 정보 기준 조회된 사용자 객체 */ public static User currentUser() { String userId = session().get(SESSION_USERID); if (StringUtils.isEmpty(userId) || !StringUtils.isNumeric(userId)) { return User.anonymous; } User foundUser = User.find.byId(Long.valueOf(userId)); if (foundUser == null) { processLogout(); return User.anonymous; } return foundUser; } /** * 사용자 정보 조회 * * when: 사용자 로그인 아이디나 아바타를 클릭할 때 사용한다. * * {@code groups}에는 여러 그룹 이름이 콤마(,)를 기준으로 들어올 수 있으며, * 각그룹에 해당하는 프로젝트 목록을 간추리고, * 그 프로젝트 목록에 포함되는 이슈, 게시물, 풀리퀘, 마일스톤 데이터를 종합하고 최근 등록일 순으로 정렬하여 보여준다. * * @param loginId 로그인ID * @return */ public static Result userInfo(String loginId, String groups, int daysAgo, String selected) { if (daysAgo == UNDEFINED) { Cookie cookie = request().cookie(DAYS_AGO_COOKIE); if (cookie != null) { daysAgo = Integer.parseInt(cookie.value()); } else { daysAgo = DAYS_AGO; response().setCookie(DAYS_AGO_COOKIE, daysAgo + ""); } } else { if (daysAgo < 0) { daysAgo = 1; } response().setCookie(DAYS_AGO_COOKIE, daysAgo + ""); } User user = User.findByLoginId(loginId); String[] groupNames = groups.trim().split(","); List<Posting> postings = new ArrayList<>(); List<Issue> issues = new ArrayList<>(); List<PullRequest> pullRequests = new ArrayList<>(); List<Milestone> milestones = new ArrayList<>(); List<Project> projects = collectProjects(loginId, user, groupNames); collectDatum(projects, postings, issues, pullRequests, milestones, daysAgo); sortDatum(postings, issues, pullRequests, milestones); sortByLastPushedDateAndName(projects); return ok(info.render(user, groupNames, projects, postings, issues, pullRequests, milestones, daysAgo, selected)); } private static void sortByLastPushedDateAndName(List<Project> projects) { Collections.sort(projects, new Comparator<Project>() { @Override public int compare(Project p1, Project p2) { int compareLastPushedDate = 0; if (p1.lastPushedDate == null && p2.lastPushedDate == null) { return p1.name.compareTo(p2.name); } if (p1.lastPushedDate == null) { return 1; } else if (p2.lastPushedDate == null) { return -1; } compareLastPushedDate = p2.lastPushedDate.compareTo(p1.lastPushedDate); if (compareLastPushedDate == 0) { return p1.name.compareTo(p2.name); } return compareLastPushedDate; } }); } private static void sortDatum(List<Posting> postings, List<Issue> issues, List<PullRequest> pullRequests, List<Milestone> milestones) { Collections.sort(issues, new Comparator<Issue>() { @Override public int compare(Issue i1, Issue i2) { return i2.createdDate.compareTo(i1.createdDate); } }); Collections.sort(postings, new Comparator<Posting>() { @Override public int compare(Posting p1, Posting p2) { return p2.createdDate.compareTo(p1.createdDate); } }); Collections.sort(pullRequests, new Comparator<PullRequest>() { @Override public int compare(PullRequest p1, PullRequest p2) { return p2.created.compareTo(p1.created); } }); Collections.sort(milestones, new Comparator<Milestone>() { @Override public int compare(Milestone m1, Milestone m2) { return m2.title.compareTo(m1.title); } }); } private static void collectDatum(List<Project> projects, List<Posting> postings, List<Issue> issues, List<PullRequest> pullRequests, List<Milestone> milestones, int daysAgo) { // collect all postings, issues, pullrequests and milesotnes that are contained in the projects. for (Project project : projects) { if (AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.READ)) { postings.addAll(Posting.findRecentlyCreatedByDaysAgo(project, daysAgo)); issues.addAll(Issue.findRecentlyOpendIssuesByDaysAgo(project, daysAgo)); pullRequests.addAll(PullRequest.findOpendPullRequestsByDaysAgo(project, daysAgo)); milestones.addAll(Milestone.findOpenMilestones(project.id)); } } } private static List<Project> collectProjects(String loginId, User user, String[] groupNames) { List<Project> projectCollection = new ArrayList<>(); // collect all projects that are included in the project groups. for (String group : groupNames) { switch (group) { case "own": addProjectNotDupped(projectCollection, Project.findProjectsCreatedByUser(loginId, null)); break; case "member": addProjectNotDupped(projectCollection, Project.findProjectsJustMemberAndNotOwner(user)); break; case "watching": addProjectNotDupped(projectCollection, user.watchingProjects); break; } } return projectCollection; } private static void addProjectNotDupped(List<Project> target, List<Project> foundProjects) { for (Project project : foundProjects) { if( !target.contains(project) ) { target.add(project); } } } /** * 사용자 정보 수정 폼으로 이동 * 현재 로그인된 사용자 기준 * * @return */ public static Result editUserInfoForm() { User user = UserApp.currentUser(); Form<User> userForm = new Form<>(User.class); userForm = userForm.fill(user); return ok(edit.render(userForm, user)); } /** * 사용자 정보 수정 * * @return */ public static Result editUserInfo() { Form<User> userForm = new Form<>(User.class).bindFromRequest("name", "email"); String newEmail = userForm.data().get("email"); String newName = userForm.data().get("name"); User user = UserApp.currentUser(); if (StringUtils.isEmpty(newEmail)) { userForm.reject("email", "user.wrongEmail.alert"); } else { if (!StringUtils.equals(user.email, newEmail) && User.isEmailExist(newEmail)) { userForm.reject("email", "user.email.duplicate"); } } if (userForm.error("email") != null) { flash(Constants.WARNING, userForm.error("email").message()); return badRequest(edit.render(userForm, user)); } user.email = newEmail; user.name = newName; try { Long avatarId = Long.valueOf(userForm.data().get("avatarId")); if (avatarId != null) { Attachment attachment = Attachment.find.byId(avatarId); String primary = attachment.mimeType.split("/")[0].toLowerCase(); if (primary.equals("image")) { - attachment.deleteAll(currentUser().avatarAsResource()); + Attachment.deleteAll(currentUser().avatarAsResource()); attachment.moveTo(currentUser().avatarAsResource()); user.avatarUrl = routes.AttachmentApp.getFile(attachment.id).url(); } } } catch (NumberFormatException e) { } user.update(); return redirect(routes.UserApp.userInfo(user.loginId, DEFAULT_GROUP, DAYS_AGO, DEFAULT_SELECTED_TAB)); } /** * 현재 사용자가 특정 프로젝트에서 탈퇴 * * @param userName 프로젝트 매니저의 로그인ID * @param projectName 프로젝트 이름 * @return */ public static Result leave(String userName, String projectName) { ProjectApp.deleteMember(userName, projectName, UserApp.currentUser().id); return redirect(routes.UserApp.userInfo(UserApp.currentUser().loginId, DEFAULT_GROUP, DAYS_AGO, DEFAULT_SELECTED_TAB)); } /** * 로그인ID 존재 여부, 로그인ID 예약어 여부 * * @param loginId 로그인ID * @return */ public static Result isUserExist(String loginId) { ObjectNode result = Json.newObject(); result.put("isExist", User.isLoginIdExist(loginId)); result.put("isReserved", ReservedWordsValidator.isReserved(loginId)); return ok(result); } /** * 이메일 존재 여부 * * @param email 이메일 * @return */ @BodyParser.Of(BodyParser.Json.class) public static Result isEmailExist(String email) { ObjectNode result = Json.newObject(); result.put("isExist", User.isEmailExist(email)); return ok(result); } /** * 비밀번호 hash 값 생성 * * @param plainTextPassword plain text * @param passwordSalt hash salt * @return hashed password */ public static String hashedPassword(String plainTextPassword, String passwordSalt) { if (plainTextPassword == null || passwordSalt == null) { return null; } return new Sha256Hash(plainTextPassword, ByteSource.Util.bytes(passwordSalt), HASH_ITERATIONS).toBase64(); } /* * 사용자 인증 * * 사용자 객체와 hash 값을 이용 */ private static User authenticate(User user, String password) { if (!user.isAnonymous()) { if (user.password.equals(password)) { return user; } } return null; } /* * 시스템 설정에서 가입 승인 여부 조회 */ private static boolean isUseSignUpConfirm(){ Configuration config = play.Play.application().configuration(); String useSignUpConfirm = config.getString("signup.require.confirm"); if (useSignUpConfirm != null && useSignUpConfirm.equals("true")) { return true; } else { return false; } } /* * 로그인 유지기능 활성화 */ private static void setupRememberMe(User user) { response().setCookie(TOKEN, user.loginId + ":" + user.password, MAX_AGE); Logger.debug("remember me enabled"); } /* * 로그아웃 처리 * * 세션 데이터 클리어 * 로그인 유지 쿠키 폐기 */ private static void processLogout() { session().clear(); response().discardCookie(TOKEN); } /* * 사용자 가입 입력 폼 유효성 체크 */ private static void validate(Form<User> newUserForm) { // loginId가 빈 값이 들어오면 안된다. if (newUserForm.field("loginId").value().trim().isEmpty()) { newUserForm.reject("loginId", "user.wrongloginId.alert"); } if (newUserForm.field("loginId").value().contains(" ")) { newUserForm.reject("loginId", "user.wrongloginId.alert"); } // password가 빈 값이 들어오면 안된다. if (newUserForm.field("password").value().trim().isEmpty()) { newUserForm.reject("password", "user.wrongPassword.alert"); } // 중복된 loginId로 가입할 수 없다. if (User.isLoginIdExist(newUserForm.field("loginId").value())) { newUserForm.reject("loginId", "user.loginId.duplicate"); } // 중복된 email로 가입할 수 없다. if (User.isEmailExist(newUserForm.field("email").value())) { newUserForm.reject("email", "user.email.duplicate"); } } /* * 신규 가입 사용자 생성 */ private static User createNewUser(User user) { RandomNumberGenerator rng = new SecureRandomNumberGenerator(); user.passwordSalt = rng.nextBytes().getBytes().toString(); user.password = hashedPassword(user.password, user.passwordSalt); user.avatarUrl = DEFAULT_AVATAR_URL; if (isUseSignUpConfirm()) { user.isLocked = true; } return user; } /* * 사용자 정보를 세션에 저장한다 (로그인 처리됨) */ private static void addUserInfoToSession(User user) { session(SESSION_USERID, String.valueOf(user.id)); session(SESSION_LOGINID, user.loginId); session(SESSION_USERNAME, user.name); } }
true
true
public static Result editUserInfo() { Form<User> userForm = new Form<>(User.class).bindFromRequest("name", "email"); String newEmail = userForm.data().get("email"); String newName = userForm.data().get("name"); User user = UserApp.currentUser(); if (StringUtils.isEmpty(newEmail)) { userForm.reject("email", "user.wrongEmail.alert"); } else { if (!StringUtils.equals(user.email, newEmail) && User.isEmailExist(newEmail)) { userForm.reject("email", "user.email.duplicate"); } } if (userForm.error("email") != null) { flash(Constants.WARNING, userForm.error("email").message()); return badRequest(edit.render(userForm, user)); } user.email = newEmail; user.name = newName; try { Long avatarId = Long.valueOf(userForm.data().get("avatarId")); if (avatarId != null) { Attachment attachment = Attachment.find.byId(avatarId); String primary = attachment.mimeType.split("/")[0].toLowerCase(); if (primary.equals("image")) { attachment.deleteAll(currentUser().avatarAsResource()); attachment.moveTo(currentUser().avatarAsResource()); user.avatarUrl = routes.AttachmentApp.getFile(attachment.id).url(); } } } catch (NumberFormatException e) { } user.update(); return redirect(routes.UserApp.userInfo(user.loginId, DEFAULT_GROUP, DAYS_AGO, DEFAULT_SELECTED_TAB)); }
public static Result editUserInfo() { Form<User> userForm = new Form<>(User.class).bindFromRequest("name", "email"); String newEmail = userForm.data().get("email"); String newName = userForm.data().get("name"); User user = UserApp.currentUser(); if (StringUtils.isEmpty(newEmail)) { userForm.reject("email", "user.wrongEmail.alert"); } else { if (!StringUtils.equals(user.email, newEmail) && User.isEmailExist(newEmail)) { userForm.reject("email", "user.email.duplicate"); } } if (userForm.error("email") != null) { flash(Constants.WARNING, userForm.error("email").message()); return badRequest(edit.render(userForm, user)); } user.email = newEmail; user.name = newName; try { Long avatarId = Long.valueOf(userForm.data().get("avatarId")); if (avatarId != null) { Attachment attachment = Attachment.find.byId(avatarId); String primary = attachment.mimeType.split("/")[0].toLowerCase(); if (primary.equals("image")) { Attachment.deleteAll(currentUser().avatarAsResource()); attachment.moveTo(currentUser().avatarAsResource()); user.avatarUrl = routes.AttachmentApp.getFile(attachment.id).url(); } } } catch (NumberFormatException e) { } user.update(); return redirect(routes.UserApp.userInfo(user.loginId, DEFAULT_GROUP, DAYS_AGO, DEFAULT_SELECTED_TAB)); }
diff --git a/src/main/java/org/mozilla/gecko/sync/net/BaseResource.java b/src/main/java/org/mozilla/gecko/sync/net/BaseResource.java index 9827cf267..01e1ccc2f 100644 --- a/src/main/java/org/mozilla/gecko/sync/net/BaseResource.java +++ b/src/main/java/org/mozilla/gecko/sync/net/BaseResource.java @@ -1,412 +1,415 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.gecko.sync.net; import java.io.BufferedReader; import java.io.IOException; import java.lang.ref.WeakReference; import java.net.URI; import java.net.URISyntaxException; import java.security.GeneralSecurityException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.net.ssl.SSLContext; import org.mozilla.gecko.sync.Logger; import ch.boye.httpclientandroidlib.Header; import ch.boye.httpclientandroidlib.HttpEntity; import ch.boye.httpclientandroidlib.HttpResponse; import ch.boye.httpclientandroidlib.HttpVersion; import ch.boye.httpclientandroidlib.auth.Credentials; import ch.boye.httpclientandroidlib.auth.UsernamePasswordCredentials; import ch.boye.httpclientandroidlib.client.AuthCache; import ch.boye.httpclientandroidlib.client.ClientProtocolException; import ch.boye.httpclientandroidlib.client.methods.HttpDelete; import ch.boye.httpclientandroidlib.client.methods.HttpGet; import ch.boye.httpclientandroidlib.client.methods.HttpPost; import ch.boye.httpclientandroidlib.client.methods.HttpPut; import ch.boye.httpclientandroidlib.client.methods.HttpRequestBase; import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest; import ch.boye.httpclientandroidlib.client.protocol.ClientContext; import ch.boye.httpclientandroidlib.conn.ClientConnectionManager; import ch.boye.httpclientandroidlib.conn.scheme.PlainSocketFactory; import ch.boye.httpclientandroidlib.conn.scheme.Scheme; import ch.boye.httpclientandroidlib.conn.scheme.SchemeRegistry; import ch.boye.httpclientandroidlib.conn.ssl.SSLSocketFactory; import ch.boye.httpclientandroidlib.impl.auth.BasicScheme; import ch.boye.httpclientandroidlib.impl.client.BasicAuthCache; import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient; import ch.boye.httpclientandroidlib.impl.conn.tsccm.ThreadSafeClientConnManager; import ch.boye.httpclientandroidlib.params.HttpConnectionParams; import ch.boye.httpclientandroidlib.params.HttpParams; import ch.boye.httpclientandroidlib.params.HttpProtocolParams; import ch.boye.httpclientandroidlib.protocol.BasicHttpContext; import ch.boye.httpclientandroidlib.protocol.HttpContext; import ch.boye.httpclientandroidlib.util.EntityUtils; /** * Provide simple HTTP access to a Sync server or similar. * Implements Basic Auth by asking its delegate for credentials. * Communicates with a ResourceDelegate to asynchronously return responses and errors. * Exposes simple get/post/put/delete methods. */ public class BaseResource implements Resource { private static final String ANDROID_LOOPBACK_IP = "10.0.2.2"; private static final int MAX_TOTAL_CONNECTIONS = 20; private static final int MAX_CONNECTIONS_PER_ROUTE = 10; private boolean retryOnFailedRequest = true; public static boolean rewriteLocalhost = true; private static final String LOG_TAG = "BaseResource"; protected URI uri; protected BasicHttpContext context; protected DefaultHttpClient client; public ResourceDelegate delegate; protected HttpRequestBase request; public String charset = "utf-8"; protected static WeakReference<HttpResponseObserver> httpResponseObserver = null; public BaseResource(String uri) throws URISyntaxException { this(uri, rewriteLocalhost); } public BaseResource(URI uri) { this(uri, rewriteLocalhost); } public BaseResource(String uri, boolean rewrite) throws URISyntaxException { this(new URI(uri), rewrite); } public BaseResource(URI uri, boolean rewrite) { if (rewrite && uri.getHost().equals("localhost")) { // Rewrite localhost URIs to refer to the special Android emulator loopback passthrough interface. Logger.debug(LOG_TAG, "Rewriting " + uri + " to point to " + ANDROID_LOOPBACK_IP + "."); try { this.uri = new URI(uri.getScheme(), uri.getUserInfo(), ANDROID_LOOPBACK_IP, uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException e) { Logger.error(LOG_TAG, "Got error rewriting URI for Android emulator.", e); } } else { this.uri = uri; } } public static synchronized HttpResponseObserver getHttpResponseObserver() { if (httpResponseObserver == null) { return null; } return httpResponseObserver.get(); } public static synchronized void setHttpResponseObserver(HttpResponseObserver newHttpResponseObserver) { if (httpResponseObserver != null) { httpResponseObserver.clear(); } httpResponseObserver = new WeakReference<HttpResponseObserver>(newHttpResponseObserver); } public URI getURI() { return this.uri; } /** * This shuts up HttpClient, which will otherwise debug log about there * being no auth cache in the context. */ private static void addAuthCacheToContext(HttpUriRequest request, HttpContext context) { AuthCache authCache = new BasicAuthCache(); // Not thread safe. context.setAttribute(ClientContext.AUTH_CACHE, authCache); } /** * Return a Header object representing an Authentication header for HTTP Basic. */ public static Header getBasicAuthHeader(final String credentials) { Credentials creds = new UsernamePasswordCredentials(credentials); // This must be UTF-8 to generate the same Basic Auth headers as desktop for non-ASCII passwords. return BasicScheme.authenticate(creds, "UTF-8", false); } /** * Apply the provided credentials string to the provided request. * @param credentials a string, "user:pass". */ private static void applyCredentials(String credentials, HttpUriRequest request, HttpContext context) { request.addHeader(getBasicAuthHeader(credentials)); Logger.trace(LOG_TAG, "Adding Basic Auth header."); } /** * Invoke this after delegate and request have been set. * @throws NoSuchAlgorithmException * @throws KeyManagementException */ private void prepareClient() throws KeyManagementException, NoSuchAlgorithmException { context = new BasicHttpContext(); // We could reuse these client instances, except that we mess around // with their parameters… so we'd need a pool of some kind. client = new DefaultHttpClient(getConnectionManager()); // TODO: Eventually we should use Apache HttpAsyncClient. It's not out of alpha yet. // Until then, we synchronously make the request, then invoke our delegate's callback. String credentials = delegate.getCredentials(); if (credentials != null) { BaseResource.applyCredentials(credentials, request, context); } addAuthCacheToContext(request, context); HttpParams params = client.getParams(); HttpConnectionParams.setConnectionTimeout(params, delegate.connectionTimeout()); HttpConnectionParams.setSoTimeout(params, delegate.socketTimeout()); HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpProtocolParams.setContentCharset(params, charset); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); delegate.addHeaders(request, client); } private static Object connManagerMonitor = new Object(); private static ClientConnectionManager connManager; /** * This method exists for test code. */ public static ClientConnectionManager enablePlainHTTPConnectionManager() { synchronized (connManagerMonitor) { ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(); connManager = cm; return cm; } } // Call within a synchronized block on connManagerMonitor. private static ClientConnectionManager enableTLSConnectionManager() throws KeyManagementException, NoSuchAlgorithmException { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, null, new SecureRandom()); SSLSocketFactory sf = new TLSSocketFactory(sslContext); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", 443, sf)); schemeRegistry.register(new Scheme("http", 80, new PlainSocketFactory())); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry); cm.setMaxTotal(MAX_TOTAL_CONNECTIONS); cm.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE); connManager = cm; return cm; } public static ClientConnectionManager getConnectionManager() throws KeyManagementException, NoSuchAlgorithmException { // TODO: shutdown. synchronized (connManagerMonitor) { if (connManager != null) { return connManager; } return enableTLSConnectionManager(); } } /** * Do some cleanup, so we don't need the stale connection check. */ public static void closeExpiredConnections() { ClientConnectionManager connectionManager; synchronized (connManagerMonitor) { connectionManager = connManager; } if (connectionManager == null) { return; } Logger.trace(LOG_TAG, "Closing expired connections."); connectionManager.closeExpiredConnections(); } public static void shutdownConnectionManager() { ClientConnectionManager connectionManager; synchronized (connManagerMonitor) { connectionManager = connManager; connManager = null; } if (connectionManager == null) { return; } Logger.debug(LOG_TAG, "Shutting down connection manager."); connectionManager.shutdown(); } private void execute() { HttpResponse response; try { response = client.execute(request, context); Logger.debug(LOG_TAG, "Response: " + response.getStatusLine().toString()); } catch (ClientProtocolException e) { delegate.handleHttpProtocolException(e); return; } catch (IOException e) { Logger.debug(LOG_TAG, "I/O exception returned from execute."); if (!retryOnFailedRequest) { delegate.handleHttpIOException(e); } else { retryRequest(); } return; } catch (Exception e) { // Bug 740731: Don't let an exception fall through. Wrapping isn't // optimal, but often the exception is treated as an Exception anyway. if (!retryOnFailedRequest) { - delegate.handleHttpIOException(new IOException(e)); + // Bug 769671: IOException(Throwable cause) was added only in API level 9. + final IOException ex = new IOException(); + ex.initCause(e); + delegate.handleHttpIOException(ex); } else { retryRequest(); } return; } // Don't retry if the observer or delegate throws! HttpResponseObserver observer = getHttpResponseObserver(); if (observer != null) { observer.observeHttpResponse(response); } delegate.handleHttpResponse(response); } private void retryRequest() { // Only retry once. retryOnFailedRequest = false; Logger.debug(LOG_TAG, "Retrying request..."); this.execute(); } private void go(HttpRequestBase request) { if (delegate == null) { throw new IllegalArgumentException("No delegate provided."); } this.request = request; try { this.prepareClient(); } catch (KeyManagementException e) { Logger.error(LOG_TAG, "Couldn't prepare client.", e); delegate.handleTransportException(e); return; } catch (NoSuchAlgorithmException e) { Logger.error(LOG_TAG, "Couldn't prepare client.", e); delegate.handleTransportException(e); return; } catch (Exception e) { // Bug 740731: Don't let an exception fall through. Wrapping isn't // optimal, but often the exception is treated as an Exception anyway. delegate.handleTransportException(new GeneralSecurityException(e)); return; } this.execute(); } @Override public void get() { Logger.debug(LOG_TAG, "HTTP GET " + this.uri.toASCIIString()); this.go(new HttpGet(this.uri)); } @Override public void delete() { Logger.debug(LOG_TAG, "HTTP DELETE " + this.uri.toASCIIString()); this.go(new HttpDelete(this.uri)); } @Override public void post(HttpEntity body) { Logger.debug(LOG_TAG, "HTTP POST " + this.uri.toASCIIString()); HttpPost request = new HttpPost(this.uri); request.setEntity(body); this.go(request); } @Override public void put(HttpEntity body) { Logger.debug(LOG_TAG, "HTTP PUT " + this.uri.toASCIIString()); HttpPut request = new HttpPut(this.uri); request.setEntity(body); this.go(request); } /** * Best-effort attempt to ensure that the entity has been fully consumed and * that the underlying stream has been closed. * * This releases the connection back to the connection pool. * * @param entity The HttpEntity to be consumed. */ public static void consumeEntity(HttpEntity entity) { try { EntityUtils.consume(entity); } catch (IOException e) { // Doesn't matter. } } /** * Best-effort attempt to ensure that the entity corresponding to the given * HTTP response has been fully consumed and that the underlying stream has * been closed. * * This releases the connection back to the connection pool. * * @param response * The HttpResponse to be consumed. */ public static void consumeEntity(HttpResponse response) { if (response == null) { return; } try { EntityUtils.consume(response.getEntity()); } catch (IOException e) { } } /** * Best-effort attempt to ensure that the entity corresponding to the given * Sync storage response has been fully consumed and that the underlying * stream has been closed. * * This releases the connection back to the connection pool. * * @param response * The SyncStorageResponse to be consumed. */ public static void consumeEntity(SyncStorageResponse response) { if (response.httpResponse() == null) { return; } consumeEntity(response.httpResponse()); } /** * Best-effort attempt to ensure that the reader has been fully consumed, so * that the underlying stream will be closed. * * This should allow the connection to be released back to the connection pool. * * @param reader The BufferedReader to be consumed. */ public static void consumeReader(BufferedReader reader) { try { reader.close(); } catch (IOException e) { // Do nothing. } } }
true
true
private void execute() { HttpResponse response; try { response = client.execute(request, context); Logger.debug(LOG_TAG, "Response: " + response.getStatusLine().toString()); } catch (ClientProtocolException e) { delegate.handleHttpProtocolException(e); return; } catch (IOException e) { Logger.debug(LOG_TAG, "I/O exception returned from execute."); if (!retryOnFailedRequest) { delegate.handleHttpIOException(e); } else { retryRequest(); } return; } catch (Exception e) { // Bug 740731: Don't let an exception fall through. Wrapping isn't // optimal, but often the exception is treated as an Exception anyway. if (!retryOnFailedRequest) { delegate.handleHttpIOException(new IOException(e)); } else { retryRequest(); } return; } // Don't retry if the observer or delegate throws! HttpResponseObserver observer = getHttpResponseObserver(); if (observer != null) { observer.observeHttpResponse(response); } delegate.handleHttpResponse(response); }
private void execute() { HttpResponse response; try { response = client.execute(request, context); Logger.debug(LOG_TAG, "Response: " + response.getStatusLine().toString()); } catch (ClientProtocolException e) { delegate.handleHttpProtocolException(e); return; } catch (IOException e) { Logger.debug(LOG_TAG, "I/O exception returned from execute."); if (!retryOnFailedRequest) { delegate.handleHttpIOException(e); } else { retryRequest(); } return; } catch (Exception e) { // Bug 740731: Don't let an exception fall through. Wrapping isn't // optimal, but often the exception is treated as an Exception anyway. if (!retryOnFailedRequest) { // Bug 769671: IOException(Throwable cause) was added only in API level 9. final IOException ex = new IOException(); ex.initCause(e); delegate.handleHttpIOException(ex); } else { retryRequest(); } return; } // Don't retry if the observer or delegate throws! HttpResponseObserver observer = getHttpResponseObserver(); if (observer != null) { observer.observeHttpResponse(response); } delegate.handleHttpResponse(response); }
diff --git a/xbean-classloader/src/main/java/org/apache/xbean/classloader/MultiParentClassLoader.java b/xbean-classloader/src/main/java/org/apache/xbean/classloader/MultiParentClassLoader.java index aca615b4..927e3999 100644 --- a/xbean-classloader/src/main/java/org/apache/xbean/classloader/MultiParentClassLoader.java +++ b/xbean-classloader/src/main/java/org/apache/xbean/classloader/MultiParentClassLoader.java @@ -1,345 +1,345 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xbean.classloader; import java.io.IOException; import java.net.URL; import java.net.URLStreamHandlerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.List; /** * A MultiParentClassLoader is a simple extension of the URLClassLoader that simply changes the single parent class * loader model to support a list of parent class loaders. Each operation that accesses a parent, has been replaced * with a operation that checks each parent in order. This getParent method of this class will always return null, * which may be interperated by the calling code to mean that this class loader is a direct child of the system class * loader. * * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public class MultiParentClassLoader extends NamedClassLoader { private final ClassLoader[] parents; private final boolean inverseClassLoading; private final String[] hiddenClasses; private final String[] nonOverridableClasses; private final String[] hiddenResources; private final String[] nonOverridableResources; /** * Creates a named class loader with no parents. * @param name the name of this class loader * @param urls the urls from which this class loader will classes and resources */ public MultiParentClassLoader(String name, URL[] urls) { this(name, urls, ClassLoader.getSystemClassLoader()); } /** * Creates a named class loader as a child of the specified parent. * @param name the name of this class loader * @param urls the urls from which this class loader will classes and resources * @param parent the parent of this class loader */ public MultiParentClassLoader(String name, URL[] urls, ClassLoader parent) { this(name, urls, new ClassLoader[] {parent}); } /** * Creates a named class loader as a child of the specified parent and using the specified URLStreamHandlerFactory * for accessing the urls.. * @param name the name of this class loader * @param urls the urls from which this class loader will classes and resources * @param parent the parent of this class loader * @param factory the URLStreamHandlerFactory used to access the urls */ public MultiParentClassLoader(String name, URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) { this(name, urls, new ClassLoader[] {parent}, factory); } /** * Creates a named class loader as a child of the specified parents. * @param name the name of this class loader * @param urls the urls from which this class loader will classes and resources * @param parents the parents of this class loader */ public MultiParentClassLoader(String name, URL[] urls, ClassLoader[] parents) { this(name, urls, parents, false, new String[0], new String[0]); } public MultiParentClassLoader(String name, URL[] urls, ClassLoader parent, boolean inverseClassLoading, String[] hiddenClasses, String[] nonOverridableClasses) { this(name, urls, new ClassLoader[]{parent}, inverseClassLoading, hiddenClasses, nonOverridableClasses); } /** * Creates a named class loader as a child of the specified parents and using the specified URLStreamHandlerFactory * for accessing the urls.. * @param name the name of this class loader * @param urls the urls from which this class loader will classes and resources * @param parents the parents of this class loader * @param factory the URLStreamHandlerFactory used to access the urls */ public MultiParentClassLoader(String name, URL[] urls, ClassLoader[] parents, URLStreamHandlerFactory factory) { super(name, urls, null, factory); this.parents = copyParents(parents); this.inverseClassLoading = false; this.hiddenClasses = new String[0]; this.nonOverridableClasses = new String[0]; this.hiddenResources = new String[0]; this.nonOverridableResources = new String[0]; } public MultiParentClassLoader(String name, URL[] urls, ClassLoader[] parents, boolean inverseClassLoading, Collection hiddenClasses, Collection nonOverridableClasses) { this(name, urls, parents, inverseClassLoading, (String[]) hiddenClasses.toArray(new String[hiddenClasses.size()]), (String[]) nonOverridableClasses.toArray(new String[nonOverridableClasses.size()])); } public MultiParentClassLoader(String name, URL[] urls, ClassLoader[] parents, boolean inverseClassLoading, String[] hiddenClasses, String[] nonOverridableClasses) { super(name, urls); this.parents = copyParents(parents); this.inverseClassLoading = inverseClassLoading; this.hiddenClasses = hiddenClasses; this.nonOverridableClasses = nonOverridableClasses; hiddenResources = toResources(hiddenClasses); nonOverridableResources = toResources(nonOverridableClasses); } private static String[] toResources(String[] classes) { String[] resources = new String[classes.length]; for (int i = 0; i < classes.length; i++) { String className = classes[i]; resources[i] = className.replace('.', '/'); } return resources; } private static ClassLoader[] copyParents(ClassLoader[] parents) { ClassLoader[] newParentsArray = new ClassLoader[parents.length]; for (int i = 0; i < parents.length; i++) { ClassLoader parent = parents[i]; if (parent == null) { throw new NullPointerException("parent[" + i + "] is null"); } newParentsArray[i] = parent; } return newParentsArray; } /** * Gets the parents of this class loader. * @return the parents of this class loader */ public ClassLoader[] getParents() { return parents; } /** * {@inheritDoc} */ protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { // // Check if class is in the loaded classes cache // Class cachedClass = findLoadedClass(name); if (cachedClass != null) { return resolveClass(cachedClass, resolve); } // // if we are using inverse class loading, check local urls first // if (inverseClassLoading && !isDestroyed() && !isNonOverridableClass(name)) { try { Class clazz = findClass(name); return resolveClass(clazz, resolve); } catch (ClassNotFoundException ignored) { } } // // Check parent class loaders // if (!isHiddenClass(name)) { for (int i = 0; i < parents.length; i++) { ClassLoader parent = parents[i]; try { Class clazz = parent.loadClass(name); return resolveClass(clazz, resolve); } catch (ClassNotFoundException ignored) { // this parent didn't have the class; try the next one } } } // // if we are not using inverse class loading, check local urls now // // don't worry about excluding non-overridable classes here... we // have alredy checked he parent and the parent didn't have the // class, so we can override now if (!isDestroyed()) { try { Class clazz = findClass(name); return resolveClass(clazz, resolve); } catch (ClassNotFoundException ignored) { } } - throw new ClassNotFoundException(name + " in classloader " + name); + throw new ClassNotFoundException(name + " in classloader " + getName()); } private boolean isNonOverridableClass(String name) { for (int i = 0; i < nonOverridableClasses.length; i++) { if (name.startsWith(nonOverridableClasses[i])) { return true; } } return false; } private boolean isHiddenClass(String name) { for (int i = 0; i < hiddenClasses.length; i++) { if (name.startsWith(hiddenClasses[i])) { return true; } } return false; } private Class resolveClass(Class clazz, boolean resolve) { if (resolve) { resolveClass(clazz); } return clazz; } /** * {@inheritDoc} */ public URL getResource(String name) { if (isDestroyed()) { return null; } // // if we are using inverse class loading, check local urls first // if (inverseClassLoading && !isDestroyed() && !isNonOverridableResource(name)) { URL url = findResource(name); if (url != null) { return url; } } // // Check parent class loaders // if (!isHiddenResource(name)) { for (int i = 0; i < parents.length; i++) { ClassLoader parent = parents[i]; URL url = parent.getResource(name); if (url != null) { return url; } } } // // if we are not using inverse class loading, check local urls now // // don't worry about excluding non-overridable resources here... we // have alredy checked he parent and the parent didn't have the // resource, so we can override now if (!isDestroyed()) { // parents didn't have the resource; attempt to load it from my urls return findResource(name); } return null; } /** * {@inheritDoc} */ public Enumeration findResources(String name) throws IOException { if (isDestroyed()) { return Collections.enumeration(Collections.EMPTY_SET); } List resources = new ArrayList(); // // if we are using inverse class loading, add the resources from local urls first // if (inverseClassLoading && !isDestroyed()) { List myResources = Collections.list(super.findResources(name)); resources.addAll(myResources); } // // Add parent resources // for (int i = 0; i < parents.length; i++) { ClassLoader parent = parents[i]; List parentResources = Collections.list(parent.getResources(name)); resources.addAll(parentResources); } // // if we are not using inverse class loading, add the resources from local urls now // if (!inverseClassLoading && !isDestroyed()) { List myResources = Collections.list(super.findResources(name)); resources.addAll(myResources); } return Collections.enumeration(resources); } private boolean isNonOverridableResource(String name) { for (int i = 0; i < nonOverridableResources.length; i++) { if (name.startsWith(nonOverridableResources[i])) { return true; } } return false; } private boolean isHiddenResource(String name) { for (int i = 0; i < hiddenResources.length; i++) { if (name.startsWith(hiddenResources[i])) { return true; } } return false; } /** * {@inheritDoc} */ public String toString() { return "[" + getClass().getName() + ":" + " name=" + getName() + " urls=" + Arrays.asList(getURLs()) + " parents=" + Arrays.asList(parents) + "]"; } }
true
true
protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { // // Check if class is in the loaded classes cache // Class cachedClass = findLoadedClass(name); if (cachedClass != null) { return resolveClass(cachedClass, resolve); } // // if we are using inverse class loading, check local urls first // if (inverseClassLoading && !isDestroyed() && !isNonOverridableClass(name)) { try { Class clazz = findClass(name); return resolveClass(clazz, resolve); } catch (ClassNotFoundException ignored) { } } // // Check parent class loaders // if (!isHiddenClass(name)) { for (int i = 0; i < parents.length; i++) { ClassLoader parent = parents[i]; try { Class clazz = parent.loadClass(name); return resolveClass(clazz, resolve); } catch (ClassNotFoundException ignored) { // this parent didn't have the class; try the next one } } } // // if we are not using inverse class loading, check local urls now // // don't worry about excluding non-overridable classes here... we // have alredy checked he parent and the parent didn't have the // class, so we can override now if (!isDestroyed()) { try { Class clazz = findClass(name); return resolveClass(clazz, resolve); } catch (ClassNotFoundException ignored) { } } throw new ClassNotFoundException(name + " in classloader " + name); }
protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { // // Check if class is in the loaded classes cache // Class cachedClass = findLoadedClass(name); if (cachedClass != null) { return resolveClass(cachedClass, resolve); } // // if we are using inverse class loading, check local urls first // if (inverseClassLoading && !isDestroyed() && !isNonOverridableClass(name)) { try { Class clazz = findClass(name); return resolveClass(clazz, resolve); } catch (ClassNotFoundException ignored) { } } // // Check parent class loaders // if (!isHiddenClass(name)) { for (int i = 0; i < parents.length; i++) { ClassLoader parent = parents[i]; try { Class clazz = parent.loadClass(name); return resolveClass(clazz, resolve); } catch (ClassNotFoundException ignored) { // this parent didn't have the class; try the next one } } } // // if we are not using inverse class loading, check local urls now // // don't worry about excluding non-overridable classes here... we // have alredy checked he parent and the parent didn't have the // class, so we can override now if (!isDestroyed()) { try { Class clazz = findClass(name); return resolveClass(clazz, resolve); } catch (ClassNotFoundException ignored) { } } throw new ClassNotFoundException(name + " in classloader " + getName()); }
diff --git a/src/main/java/org/jboss/pressgang/ccms/contentspec/client/commands/PushTranslationCommand.java b/src/main/java/org/jboss/pressgang/ccms/contentspec/client/commands/PushTranslationCommand.java index 468bbdd..fdb5b4b 100644 --- a/src/main/java/org/jboss/pressgang/ccms/contentspec/client/commands/PushTranslationCommand.java +++ b/src/main/java/org/jboss/pressgang/ccms/contentspec/client/commands/PushTranslationCommand.java @@ -1,694 +1,698 @@ package org.jboss.pressgang.ccms.contentspec.client.commands; import static com.google.common.base.Strings.isNullOrEmpty; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import org.jboss.pressgang.ccms.contentspec.ContentSpec; import org.jboss.pressgang.ccms.contentspec.SpecTopic; import org.jboss.pressgang.ccms.contentspec.builder.constants.BuilderConstants; import org.jboss.pressgang.ccms.contentspec.client.commands.base.BaseCommandImpl; import org.jboss.pressgang.ccms.contentspec.client.config.ClientConfiguration; import org.jboss.pressgang.ccms.contentspec.client.config.ContentSpecConfiguration; import org.jboss.pressgang.ccms.contentspec.client.config.ZanataServerConfiguration; import org.jboss.pressgang.ccms.contentspec.client.constants.Constants; import org.jboss.pressgang.ccms.contentspec.client.processor.ClientContentSpecProcessor; import org.jboss.pressgang.ccms.contentspec.client.utils.ClientUtilities; import org.jboss.pressgang.ccms.contentspec.processor.ContentSpecParser; import org.jboss.pressgang.ccms.contentspec.processor.structures.ProcessingOptions; import org.jboss.pressgang.ccms.contentspec.structures.StringToCSNodeCollection; import org.jboss.pressgang.ccms.contentspec.utils.CSTransformer; import org.jboss.pressgang.ccms.contentspec.utils.EntityUtilities; import org.jboss.pressgang.ccms.contentspec.utils.TranslationUtilities; import org.jboss.pressgang.ccms.contentspec.utils.logging.ErrorLoggerManager; import org.jboss.pressgang.ccms.provider.ContentSpecProvider; import org.jboss.pressgang.ccms.provider.DataProviderFactory; import org.jboss.pressgang.ccms.provider.TopicProvider; import org.jboss.pressgang.ccms.provider.TranslatedContentSpecProvider; import org.jboss.pressgang.ccms.provider.TranslatedTopicProvider; import org.jboss.pressgang.ccms.utils.common.DocBookUtilities; import org.jboss.pressgang.ccms.utils.common.HashUtilities; import org.jboss.pressgang.ccms.utils.common.XMLUtilities; import org.jboss.pressgang.ccms.utils.structures.Pair; import org.jboss.pressgang.ccms.utils.structures.StringToNodeCollection; import org.jboss.pressgang.ccms.wrapper.ContentSpecWrapper; import org.jboss.pressgang.ccms.wrapper.TopicWrapper; import org.jboss.pressgang.ccms.wrapper.TranslatedCSNodeWrapper; import org.jboss.pressgang.ccms.wrapper.TranslatedContentSpecWrapper; import org.jboss.pressgang.ccms.wrapper.TranslatedTopicWrapper; import org.jboss.pressgang.ccms.zanata.ZanataConstants; import org.jboss.pressgang.ccms.zanata.ZanataDetails; import org.jboss.pressgang.ccms.zanata.ZanataInterface; import org.w3c.dom.Document; import org.w3c.dom.Entity; import org.zanata.common.ContentType; import org.zanata.common.LocaleId; import org.zanata.common.ResourceType; import org.zanata.rest.dto.resource.Resource; import org.zanata.rest.dto.resource.TextFlow; @Parameters(resourceBundle = "commands", commandDescriptionKey = "PUSH_TRANSLATION") public class PushTranslationCommand extends BaseCommandImpl { @Parameter(metaVar = "[ID]") private List<Integer> ids = new ArrayList<Integer>(); @Parameter(names = Constants.ZANATA_SERVER_LONG_PARAM, descriptionKey = "ZANATA_SERVER", metaVar = "<URL>") private String zanataUrl = null; @Parameter(names = Constants.ZANATA_PROJECT_LONG_PARAM, descriptionKey = "ZANATA_PROJECT", metaVar = "<PROJECT>") private String zanataProject = null; @Parameter(names = Constants.ZANATA_PROJECT_VERSION_LONG_PARAM, descriptionKey = "ZANATA_PROJECT_VERSION", metaVar = "<VERSION>") private String zanataVersion = null; @Parameter(names = Constants.CONTENT_SPEC_ONLY_LONG_PARAM, descriptionKey = "PUSH_TRANSLATION_CONTENT_SPEC_ONLY") private Boolean contentSpecOnly = false; @Parameter(names = {Constants.YES_LONG_PARAM, Constants.YES_SHORT_PARAM}, descriptionKey = "ANSWER_YES") private Boolean answerYes = false; @Parameter(names = Constants.DISABLE_SSL_CERT_CHECK, descriptionKey = "DISABLE_SSL_CERT_CHECK") private Boolean disableSSLCert = false; private ClientContentSpecProcessor csp; public PushTranslationCommand(final JCommander parser, final ContentSpecConfiguration cspConfig, final ClientConfiguration clientConfig) { super(parser, cspConfig, clientConfig); } @Override public String getCommandName() { return Constants.PUSH_TRANSLATION_COMMAND_NAME; } public List<Integer> getIds() { return ids; } public void setIds(final List<Integer> ids) { this.ids = ids; } public String getZanataUrl() { return zanataUrl; } public void setZanataUrl(final String zanataUrl) { this.zanataUrl = zanataUrl; } public String getZanataProject() { return zanataProject; } public void setZanataProject(final String zanataProject) { this.zanataProject = zanataProject; } public String getZanataVersion() { return zanataVersion; } public void setZanataVersion(final String zanataVersion) { this.zanataVersion = zanataVersion; } public Boolean getAnswerYes() { return answerYes; } public void setAnswerYes(Boolean answerYes) { this.answerYes = answerYes; } public Boolean getContentSpecOnly() { return contentSpecOnly; } public void setContentSpecOnly(Boolean contentSpecOnly) { this.contentSpecOnly = contentSpecOnly; } public Boolean getDisableSSLCert() { return disableSSLCert; } public void setDisableSSLCert(Boolean disableSSLCert) { this.disableSSLCert = disableSSLCert; } @Override public boolean validateServerUrl() { setupZanataOptions(); if (!super.validateServerUrl()) return false; final ZanataDetails zanataDetails = getCspConfig().getZanataDetails(); // Print the zanata server url JCommander.getConsole().println(ClientUtilities.getMessage("ZANATA_WEBSERVICE_MSG", zanataDetails.getServer())); // Test that the server address is valid if (!ClientUtilities.validateServerExists(zanataDetails.getServer(), getDisableSSLCert())) { // Print a line to separate content JCommander.getConsole().println(""); printErrorAndShutdown(Constants.EXIT_NO_SERVER, ClientUtilities.getMessage("ERROR_UNABLE_TO_FIND_SERVER_MSG"), false); } return true; } /** * Sets the zanata options applied by the command line * to the options that were set via configuration files. */ protected void setupZanataOptions() { // Set the zanata url if (getZanataUrl() != null) { ZanataServerConfiguration zanataConfig = null; // Find the zanata server if the url is a reference to the zanata server name for (final String serverName : getClientConfig().getZanataServers().keySet()) { if (serverName.equals(getZanataUrl())) { zanataConfig = getClientConfig().getZanataServers().get(serverName); setZanataUrl(zanataConfig.getUrl()); break; } } getCspConfig().getZanataDetails().setServer(ClientUtilities.fixHostURL(getZanataUrl())); if (zanataConfig != null) { getCspConfig().getZanataDetails().setToken(zanataConfig.getToken()); getCspConfig().getZanataDetails().setUsername(zanataConfig.getUsername()); } } // Set the zanata project if (getZanataProject() != null) { getCspConfig().getZanataDetails().setProject(getZanataProject()); } // Set the zanata version if (getZanataVersion() != null) { getCspConfig().getZanataDetails().setVersion(getZanataVersion()); } } protected boolean isValid() { final ZanataDetails zanataDetails = getCspConfig().getZanataDetails(); // Check that we even have some zanata details. if (zanataDetails == null) return false; // Check that none of the fields are invalid. if (zanataDetails.getServer() == null || zanataDetails.getServer().isEmpty() || zanataDetails.getProject() == null || zanataDetails.getProject().isEmpty() || zanataDetails.getVersion() == null || zanataDetails.getVersion().isEmpty() || zanataDetails.getToken() == null || zanataDetails.getToken().isEmpty() || zanataDetails.getUsername() == null || zanataDetails.getUsername().isEmpty()) { return false; } // At this point the zanata details are valid, so save the details. System.setProperty(ZanataConstants.ZANATA_SERVER_PROPERTY, zanataDetails.getServer()); System.setProperty(ZanataConstants.ZANATA_PROJECT_PROPERTY, zanataDetails.getProject()); System.setProperty(ZanataConstants.ZANATA_PROJECT_VERSION_PROPERTY, zanataDetails.getVersion()); System.setProperty(ZanataConstants.ZANATA_USERNAME_PROPERTY, zanataDetails.getUsername()); System.setProperty(ZanataConstants.ZANATA_TOKEN_PROPERTY, zanataDetails.getToken()); return true; } @Override public void process() { final ContentSpecProvider contentSpecProvider = getProviderFactory().getProvider(ContentSpecProvider.class); final TopicProvider topicProvider = getProviderFactory().getProvider(TopicProvider.class); // Load the ids and validate that one and only one exists ClientUtilities.prepareAndValidateIds(this, getCspConfig(), getIds()); // Check that the zanata details are valid if (!isValid()) { printErrorAndShutdown(Constants.EXIT_CONFIG_ERROR, ClientUtilities.getMessage("ERROR_PUSH_NO_ZANATA_DETAILS_MSG"), false); } // Good point to check for a shutdown allowShutdownToContinueIfRequested(); final ContentSpecWrapper contentSpecEntity = ClientUtilities.getContentSpecEntity(contentSpecProvider, ids.get(0), null); if (contentSpecEntity == null) { printErrorAndShutdown(Constants.EXIT_FAILURE, ClientUtilities.getMessage("ERROR_NO_ID_FOUND_MSG"), false); } // Check that the content spec isn't a failed one if (contentSpecEntity.getFailed() != null) { printErrorAndShutdown(Constants.EXIT_FAILURE, ClientUtilities.getMessage("ERROR_INVALID_CONTENT_SPEC_MSG"), false); } // Transform the content spec final ContentSpec contentSpec = CSTransformer.transform(contentSpecEntity, getProviderFactory(), INCLUDE_CHECKSUMS); // Setup the processing options final ProcessingOptions processingOptions = new ProcessingOptions(); processingOptions.setValidating(true); processingOptions.setIgnoreChecksum(true); processingOptions.setAllowNewTopics(false); // Validate and parse the Content Specification final ErrorLoggerManager loggerManager = new ErrorLoggerManager(); csp = new ClientContentSpecProcessor(getProviderFactory(), loggerManager, processingOptions); boolean success = csp.processContentSpec(contentSpec, getUsername(), ContentSpecParser.ParsingMode.EITHER); // Print the error/warning messages JCommander.getConsole().println(loggerManager.generateLogs()); // Check that everything validated fine if (!success) { shutdown(Constants.EXIT_TOPIC_INVALID); } // Good point to check for a shutdown allowShutdownToContinueIfRequested(); // Initialise the topic wrappers in the spec topics initialiseSpecTopics(topicProvider, contentSpec); // Good point to check for a shutdown allowShutdownToContinueIfRequested(); if (!pushToZanata(getProviderFactory(), contentSpec, contentSpecEntity)) { printErrorAndShutdown(Constants.EXIT_FAILURE, ClientUtilities.getMessage("ERROR_ZANATA_PUSH_FAILED_MSG"), false); shutdown(Constants.EXIT_FAILURE); } else { JCommander.getConsole().println(ClientUtilities.getMessage("SUCCESSFUL_ZANATA_PUSH_MSG")); } } @Override public boolean loadFromCSProcessorCfg() { return ids.size() == 0; } protected void initialiseSpecTopics(final TopicProvider topicProvider, final ContentSpec contentSpec) { final List<SpecTopic> specTopics = contentSpec.getSpecTopics(); for (final SpecTopic specTopic : specTopics) { if (specTopic.getDBId() != null && specTopic.getDBId() > 0 && specTopic.getRevision() == null) { specTopic.setTopic(topicProvider.getTopic(specTopic.getDBId())); } else if (specTopic.getDBId() != null && specTopic.getDBId() > 0 && specTopic.getRevision() != null) { specTopic.setTopic(topicProvider.getTopic(specTopic.getDBId(), specTopic.getRevision())); } } } /** * Pushes a content spec and its topics to zanata. * * @param providerFactory * @param contentSpec * @param contentSpecEntity * @return True if the push was successful otherwise false. */ protected boolean pushToZanata(final DataProviderFactory providerFactory, final ContentSpec contentSpec, final ContentSpecWrapper contentSpecEntity) { final List<Entity> entities = XMLUtilities.parseEntitiesFromString(contentSpec.getEntities()); final Map<TopicWrapper, SpecTopic> topicToSpecTopic = new HashMap<TopicWrapper, SpecTopic>(); boolean error = false; final ZanataInterface zanataInterface = new ZanataInterface(0.2, getDisableSSLCert()); // Convert all the topics to DOM Documents first so we know if any are invalid final Map<Pair<Integer, Integer>, TopicWrapper> topics = new HashMap<Pair<Integer, Integer>, TopicWrapper>(); final List<SpecTopic> specTopics = contentSpec.getSpecTopics(); for (final SpecTopic specTopic : specTopics) { final TopicWrapper topic = (TopicWrapper) specTopic.getTopic(); final Pair<Integer, Integer> topicId = new Pair<Integer, Integer>(topic.getId(), topic.getRevision()); // Only process the topic if it hasn't already been added, since the same topic can exist twice if (!topics.containsKey(topicId)) { topics.put(topicId, topic); // Convert the XML String into a DOM object. Document doc = null; try { doc = XMLUtilities.convertStringToDocument(topic.getXml()); } catch (Exception e) { // Do Nothing as we handle the error below. } if (doc == null) { JCommander.getConsole().println( "ERROR: Topic ID " + topic.getId() + ", Revision " + topic.getRevision() + " does not have valid XML"); error = true; } else { specTopic.setXMLDocument(doc); topicToSpecTopic.put(topic, specTopic); } } // Good point to check for a shutdown allowShutdownToContinueIfRequested(); } // Return if creating the documents failed if (error) { return false; } // Good point to check for a shutdown allowShutdownToContinueIfRequested(); final float total = getContentSpecOnly() ? 1 : (topics.size() + 1); float current = 0; final int showPercent = 5; int lastPercent = 0; final String answer; if (getAnswerYes()) { JCommander.getConsole().println("Pushing " + ((int) total) + " topics to zanata."); answer = "yes"; } else { JCommander.getConsole().println("You are about to push " + ((int) total) + " topics to zanata. Continue? (Yes/No)"); answer = JCommander.getConsole().readLine(); } final Map<MessageType, List<String>> messages = new HashMap<MessageType, List<String>>(); messages.put(MessageType.WARNING, new ArrayList<String>()); messages.put(MessageType.ERROR, new ArrayList<String>()); if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) { JCommander.getConsole().println("Starting to push topics to zanata..."); // Upload the content specification to zanata first so we can reference the nodes when pushing topics final TranslatedContentSpecWrapper translatedContentSpec = pushContentSpecToZanata(providerFactory, contentSpecEntity, zanataInterface, messages, entities); if (translatedContentSpec == null) { error = true; } else if (!getContentSpecOnly()) { // Loop through each topic and upload it to zanata for (final Entry<TopicWrapper, SpecTopic> topicEntry : topicToSpecTopic.entrySet()) { ++current; final int percent = Math.round(current / total * 100); if (percent - lastPercent >= showPercent) { lastPercent = percent; JCommander.getConsole().println("\tPushing topics to zanata " + percent + "% Done"); } final SpecTopic specTopic = topicEntry.getValue(); // Find the matching translated CSNode and if one can't be found then produce an error. final TranslatedCSNodeWrapper translatedCSNode = findTopicTranslatedCSNode(translatedContentSpec, specTopic); if (translatedCSNode == null) { final TopicWrapper topic = (TopicWrapper) specTopic.getTopic(); messages.get(MessageType.ERROR).add( "Topic ID " + topic.getId() + ", Revision " + topic.getRevision() + " failed to be created in Zanata."); error = true; } else { if (!pushTopicToZanata(providerFactory, contentSpec, specTopic, translatedCSNode, zanataInterface, messages, entities)) { error = true; } } } } } // Print the info/error messages if (messages.size() > 0) { JCommander.getConsole().println("Output:"); // Print the warning messages first and then any errors - JCommander.getConsole().println("Warnings:"); - for (final String message : messages.get(MessageType.WARNING)) { - JCommander.getConsole().println("\t" + message); + if (messages.containsKey(MessageType.WARNING)) { + JCommander.getConsole().println("Warnings:"); + for (final String message : messages.get(MessageType.WARNING)) { + JCommander.getConsole().println("\t" + message); + } } - JCommander.getConsole().println("Errors:"); - for (final String message : messages.get(MessageType.ERROR)) { - JCommander.getConsole().println("\t" + message); + if (messages.containsKey(MessageType.ERROR)) { + JCommander.getConsole().println("Errors:"); + for (final String message : messages.get(MessageType.ERROR)) { + JCommander.getConsole().println("\t" + message); + } } } return !error; } protected TranslatedCSNodeWrapper findTopicTranslatedCSNode(final TranslatedContentSpecWrapper translatedContentSpec, final SpecTopic specTopic) { final List<TranslatedCSNodeWrapper> translatedCSNodes = translatedContentSpec.getTranslatedNodes().getItems(); for (final TranslatedCSNodeWrapper translatedCSNode : translatedCSNodes) { if (specTopic.getUniqueId() != null && specTopic.getUniqueId().equals(translatedCSNode.getNodeId().toString())) { return translatedCSNode; } } return null; } /** * @param providerFactory * @param contentSpec * @param specTopic * @param zanataInterface * @param messages @return True if the topic was pushed successful otherwise false. * @param entities */ protected boolean pushTopicToZanata(final DataProviderFactory providerFactory, ContentSpec contentSpec, final SpecTopic specTopic, final TranslatedCSNodeWrapper translatedCSNode, final ZanataInterface zanataInterface, final Map<MessageType, List<String>> messages, final List<Entity> entities) { final TopicWrapper topic = (TopicWrapper) specTopic.getTopic(); final Document doc = specTopic.getXMLDocument(); boolean error = false; // Get the condition if the xml has any conditions boolean xmlHasConditions = !DocBookUtilities.getConditionNodes(doc).isEmpty(); final String condition = xmlHasConditions ? specTopic.getConditionStatement(true) : null; // Process the conditions, if any exist, to remove any nodes that wouldn't be seen for the content spec. DocBookUtilities.processConditions(condition, doc, BuilderConstants.DEFAULT_CONDITION); // Remove any custom entities, since they cause massive translation issues. String customEntities = null; if (!entities.isEmpty()) { try { if (TranslationUtilities.resolveCustomTopicEntities(entities, doc)) { customEntities = contentSpec.getEntities(); } } catch (Exception e) { } } // Update the topics XML topic.setXml(XMLUtilities.convertNodeToString(doc.getDocumentElement(), true)); // Create the zanata id based on whether a condition has been specified or not final boolean csNodeSpecificTopic = !isNullOrEmpty(condition) || !isNullOrEmpty(customEntities); final String zanataId = getTopicZanataId(specTopic, translatedCSNode, csNodeSpecificTopic); // Check if a translated topic already exists final boolean translatedTopicExists = EntityUtilities.getTranslatedTopicByTopicAndNodeId(providerFactory, topic.getId(), topic.getRevision(), csNodeSpecificTopic ? translatedCSNode.getId() : null, topic.getLocale()) != null; // Check if the zanata document already exists, if it does than the topic can be ignored. final Resource zanataFile = zanataInterface.getZanataResource(zanataId); if (zanataFile == null) { // Create the document to be created in Zanata final Resource resource = new Resource(); resource.setContentType(ContentType.TextPlain); resource.setLang(LocaleId.fromJavaName(topic.getLocale())); resource.setName(zanataId); resource.setRevision(1); resource.setType(ResourceType.FILE); // Get the translatable nodes final List<StringToNodeCollection> translatableStrings = XMLUtilities.getTranslatableStringsV2(doc, false); // Add the translatable nodes to the zanata document for (final StringToNodeCollection translatableStringData : translatableStrings) { final String translatableString = translatableStringData.getTranslationString(); if (!translatableString.trim().isEmpty()) { final TextFlow textFlow = new TextFlow(); textFlow.setContents(translatableString); textFlow.setLang(LocaleId.fromJavaName(topic.getLocale())); textFlow.setId(HashUtilities.generateMD5(translatableString)); textFlow.setRevision(1); resource.getTextFlows().add(textFlow); } } // Create the document in zanata and then in PressGang if the document was successfully created in Zanata. if (!zanataInterface.createFile(resource)) { messages.get(MessageType.ERROR).add("Topic ID " + topic.getId() + ", Revision " + topic.getRevision() + " failed to be " + "created in Zanata."); error = true; } else if (!translatedTopicExists) { createPressGangTranslatedTopic(providerFactory, topic, condition, customEntities, translatedCSNode, messages); } } else if (!translatedTopicExists) { createPressGangTranslatedTopic(providerFactory, topic, condition, customEntities, translatedCSNode, messages); } else { messages.get(MessageType.WARNING).add("Topic ID " + topic.getId() + ", Revision " + topic.getRevision() + " already exists - " + "Skipping."); } return !error; } protected boolean createPressGangTranslatedTopic(final DataProviderFactory providerFactory, final TopicWrapper topic, String condition, String customEntities, final TranslatedCSNodeWrapper translatedCSNode, final Map<MessageType, List<String>> messages) { final TranslatedTopicProvider translatedTopicProvider = providerFactory.getProvider(TranslatedTopicProvider.class); // Create the Translated Topic based on if it has a condition/custom entity or not. final TranslatedTopicWrapper translatedTopic; if (condition == null && customEntities == null) { translatedTopic = TranslationUtilities.createTranslatedTopic(providerFactory, topic, null, null, null); } else { translatedTopic = TranslationUtilities.createTranslatedTopic(providerFactory, topic, translatedCSNode, condition, customEntities); } // Save the Translated Topic try { if (translatedTopicProvider.createTranslatedTopic(translatedTopic) == null) { messages.get(MessageType.ERROR).add("Topic ID " + topic.getId() + ", Revision " + topic.getRevision() + " failed to be " + "created in PressGang."); return false; } } catch (Exception e) { messages.get(MessageType.ERROR).add( "Topic ID " + topic.getId() + ", Revision " + topic.getRevision() + " failed to be created " + "in PressGang."); return false; } return true; } /** * Gets the Zanata ID for a topic based on whether or not the topic has any conditional text. * * @param specTopic The topic to create the Zanata ID for. * @param translatedCSNode * @param csNodeSpecific If the Topic the Zanata ID is being created for is specific to the translated CS Node. That is that it * either has conditions, or custom entities. * @return The unique Zanata ID that can be used to create a document in Zanata. */ protected String getTopicZanataId(final SpecTopic specTopic, final TranslatedCSNodeWrapper translatedCSNode, boolean csNodeSpecific) { final TopicWrapper topic = (TopicWrapper) specTopic.getTopic(); // Create the zanata id based on whether a condition has been specified or not final String zanataId; if (csNodeSpecific) { zanataId = topic.getId() + "-" + topic.getRevision() + "-" + translatedCSNode.getId(); } else { zanataId = topic.getId() + "-" + topic.getRevision(); } return zanataId; } /** * @param providerFactory * @param contentSpecEntity * @param zanataInterface * @param messages * @param entities * @return */ protected TranslatedContentSpecWrapper pushContentSpecToZanata(final DataProviderFactory providerFactory, final ContentSpecWrapper contentSpecEntity, final ZanataInterface zanataInterface, final Map<MessageType, List<String>> messages, final List<Entity> entities) { final String zanataId = "CS" + contentSpecEntity.getId() + "-" + contentSpecEntity.getRevision(); final Resource zanataFile = zanataInterface.getZanataResource(zanataId); TranslatedContentSpecWrapper translatedContentSpec = EntityUtilities.getTranslatedContentSpecById(providerFactory, contentSpecEntity.getId(), contentSpecEntity.getRevision()); // Resolve any custom entities that might exist TranslationUtilities.resolveCustomContentSpecEntities(entities, contentSpecEntity); if (zanataFile == null) { final Resource resource = new Resource(); resource.setContentType(ContentType.TextPlain); resource.setLang(LocaleId.fromJavaName(contentSpecEntity.getLocale())); resource.setName(zanataId); resource.setRevision(1); resource.setType(ResourceType.FILE); final List<StringToCSNodeCollection> translatableStrings = TranslationUtilities.getTranslatableStrings(contentSpecEntity, false); for (final StringToCSNodeCollection translatableStringData : translatableStrings) { final String translatableString = translatableStringData.getTranslationString(); if (!translatableString.trim().isEmpty()) { final TextFlow textFlow = new TextFlow(); textFlow.setContents(translatableString); textFlow.setLang(LocaleId.fromJavaName(contentSpecEntity.getLocale())); textFlow.setId(HashUtilities.generateMD5(translatableString)); textFlow.setRevision(1); resource.getTextFlows().add(textFlow); } } // Create the document in Zanata if (!zanataInterface.createFile(resource)) { messages.get(MessageType.ERROR).add("Content Spec ID " + contentSpecEntity.getId() + ", " + "Revision " + contentSpecEntity.getRevision() + " " + "failed to be created in Zanata."); return null; } else if (translatedContentSpec == null) { return createPressGangTranslatedContentSpec(providerFactory, contentSpecEntity, messages); } } else if (translatedContentSpec == null) { return createPressGangTranslatedContentSpec(providerFactory, contentSpecEntity, messages); } else { messages.get(MessageType.WARNING).add("Content Spec ID " + contentSpecEntity.getId() + ", " + "Revision " + contentSpecEntity.getRevision() + " already " + "exists - Skipping."); } return translatedContentSpec; } protected TranslatedContentSpecWrapper createPressGangTranslatedContentSpec(final DataProviderFactory providerFactory, final ContentSpecWrapper contentSpecEntity, final Map<MessageType, List<String>> messages) { final TranslatedContentSpecProvider translatedContentSpecProvider = providerFactory.getProvider( TranslatedContentSpecProvider.class); // Create the Translated Content Spec and it's nodes final TranslatedContentSpecWrapper newTranslatedContentSpec = TranslationUtilities.createTranslatedContentSpec(providerFactory, contentSpecEntity); try { // Save the translated content spec final TranslatedContentSpecWrapper translatedContentSpec = translatedContentSpecProvider.createTranslatedContentSpec( newTranslatedContentSpec); if (translatedContentSpec == null) { messages.get(MessageType.ERROR).add("Content Spec ID" + contentSpecEntity.getId() + ", " + "Revision " + contentSpecEntity.getRevision() + " failed to be created in PressGang."); return null; } else { return translatedContentSpec; } } catch (Exception e) { messages.get(MessageType.ERROR).add( "Content Spec ID " + contentSpecEntity.getId() + ", Revision " + contentSpecEntity.getRevision() + " failed to be created in PressGang."); return null; } } @Override public boolean requiresExternalConnection() { return true; } private static enum MessageType { WARNING, ERROR } }
false
true
protected boolean pushToZanata(final DataProviderFactory providerFactory, final ContentSpec contentSpec, final ContentSpecWrapper contentSpecEntity) { final List<Entity> entities = XMLUtilities.parseEntitiesFromString(contentSpec.getEntities()); final Map<TopicWrapper, SpecTopic> topicToSpecTopic = new HashMap<TopicWrapper, SpecTopic>(); boolean error = false; final ZanataInterface zanataInterface = new ZanataInterface(0.2, getDisableSSLCert()); // Convert all the topics to DOM Documents first so we know if any are invalid final Map<Pair<Integer, Integer>, TopicWrapper> topics = new HashMap<Pair<Integer, Integer>, TopicWrapper>(); final List<SpecTopic> specTopics = contentSpec.getSpecTopics(); for (final SpecTopic specTopic : specTopics) { final TopicWrapper topic = (TopicWrapper) specTopic.getTopic(); final Pair<Integer, Integer> topicId = new Pair<Integer, Integer>(topic.getId(), topic.getRevision()); // Only process the topic if it hasn't already been added, since the same topic can exist twice if (!topics.containsKey(topicId)) { topics.put(topicId, topic); // Convert the XML String into a DOM object. Document doc = null; try { doc = XMLUtilities.convertStringToDocument(topic.getXml()); } catch (Exception e) { // Do Nothing as we handle the error below. } if (doc == null) { JCommander.getConsole().println( "ERROR: Topic ID " + topic.getId() + ", Revision " + topic.getRevision() + " does not have valid XML"); error = true; } else { specTopic.setXMLDocument(doc); topicToSpecTopic.put(topic, specTopic); } } // Good point to check for a shutdown allowShutdownToContinueIfRequested(); } // Return if creating the documents failed if (error) { return false; } // Good point to check for a shutdown allowShutdownToContinueIfRequested(); final float total = getContentSpecOnly() ? 1 : (topics.size() + 1); float current = 0; final int showPercent = 5; int lastPercent = 0; final String answer; if (getAnswerYes()) { JCommander.getConsole().println("Pushing " + ((int) total) + " topics to zanata."); answer = "yes"; } else { JCommander.getConsole().println("You are about to push " + ((int) total) + " topics to zanata. Continue? (Yes/No)"); answer = JCommander.getConsole().readLine(); } final Map<MessageType, List<String>> messages = new HashMap<MessageType, List<String>>(); messages.put(MessageType.WARNING, new ArrayList<String>()); messages.put(MessageType.ERROR, new ArrayList<String>()); if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) { JCommander.getConsole().println("Starting to push topics to zanata..."); // Upload the content specification to zanata first so we can reference the nodes when pushing topics final TranslatedContentSpecWrapper translatedContentSpec = pushContentSpecToZanata(providerFactory, contentSpecEntity, zanataInterface, messages, entities); if (translatedContentSpec == null) { error = true; } else if (!getContentSpecOnly()) { // Loop through each topic and upload it to zanata for (final Entry<TopicWrapper, SpecTopic> topicEntry : topicToSpecTopic.entrySet()) { ++current; final int percent = Math.round(current / total * 100); if (percent - lastPercent >= showPercent) { lastPercent = percent; JCommander.getConsole().println("\tPushing topics to zanata " + percent + "% Done"); } final SpecTopic specTopic = topicEntry.getValue(); // Find the matching translated CSNode and if one can't be found then produce an error. final TranslatedCSNodeWrapper translatedCSNode = findTopicTranslatedCSNode(translatedContentSpec, specTopic); if (translatedCSNode == null) { final TopicWrapper topic = (TopicWrapper) specTopic.getTopic(); messages.get(MessageType.ERROR).add( "Topic ID " + topic.getId() + ", Revision " + topic.getRevision() + " failed to be created in Zanata."); error = true; } else { if (!pushTopicToZanata(providerFactory, contentSpec, specTopic, translatedCSNode, zanataInterface, messages, entities)) { error = true; } } } } } // Print the info/error messages if (messages.size() > 0) { JCommander.getConsole().println("Output:"); // Print the warning messages first and then any errors JCommander.getConsole().println("Warnings:"); for (final String message : messages.get(MessageType.WARNING)) { JCommander.getConsole().println("\t" + message); } JCommander.getConsole().println("Errors:"); for (final String message : messages.get(MessageType.ERROR)) { JCommander.getConsole().println("\t" + message); } } return !error; }
protected boolean pushToZanata(final DataProviderFactory providerFactory, final ContentSpec contentSpec, final ContentSpecWrapper contentSpecEntity) { final List<Entity> entities = XMLUtilities.parseEntitiesFromString(contentSpec.getEntities()); final Map<TopicWrapper, SpecTopic> topicToSpecTopic = new HashMap<TopicWrapper, SpecTopic>(); boolean error = false; final ZanataInterface zanataInterface = new ZanataInterface(0.2, getDisableSSLCert()); // Convert all the topics to DOM Documents first so we know if any are invalid final Map<Pair<Integer, Integer>, TopicWrapper> topics = new HashMap<Pair<Integer, Integer>, TopicWrapper>(); final List<SpecTopic> specTopics = contentSpec.getSpecTopics(); for (final SpecTopic specTopic : specTopics) { final TopicWrapper topic = (TopicWrapper) specTopic.getTopic(); final Pair<Integer, Integer> topicId = new Pair<Integer, Integer>(topic.getId(), topic.getRevision()); // Only process the topic if it hasn't already been added, since the same topic can exist twice if (!topics.containsKey(topicId)) { topics.put(topicId, topic); // Convert the XML String into a DOM object. Document doc = null; try { doc = XMLUtilities.convertStringToDocument(topic.getXml()); } catch (Exception e) { // Do Nothing as we handle the error below. } if (doc == null) { JCommander.getConsole().println( "ERROR: Topic ID " + topic.getId() + ", Revision " + topic.getRevision() + " does not have valid XML"); error = true; } else { specTopic.setXMLDocument(doc); topicToSpecTopic.put(topic, specTopic); } } // Good point to check for a shutdown allowShutdownToContinueIfRequested(); } // Return if creating the documents failed if (error) { return false; } // Good point to check for a shutdown allowShutdownToContinueIfRequested(); final float total = getContentSpecOnly() ? 1 : (topics.size() + 1); float current = 0; final int showPercent = 5; int lastPercent = 0; final String answer; if (getAnswerYes()) { JCommander.getConsole().println("Pushing " + ((int) total) + " topics to zanata."); answer = "yes"; } else { JCommander.getConsole().println("You are about to push " + ((int) total) + " topics to zanata. Continue? (Yes/No)"); answer = JCommander.getConsole().readLine(); } final Map<MessageType, List<String>> messages = new HashMap<MessageType, List<String>>(); messages.put(MessageType.WARNING, new ArrayList<String>()); messages.put(MessageType.ERROR, new ArrayList<String>()); if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) { JCommander.getConsole().println("Starting to push topics to zanata..."); // Upload the content specification to zanata first so we can reference the nodes when pushing topics final TranslatedContentSpecWrapper translatedContentSpec = pushContentSpecToZanata(providerFactory, contentSpecEntity, zanataInterface, messages, entities); if (translatedContentSpec == null) { error = true; } else if (!getContentSpecOnly()) { // Loop through each topic and upload it to zanata for (final Entry<TopicWrapper, SpecTopic> topicEntry : topicToSpecTopic.entrySet()) { ++current; final int percent = Math.round(current / total * 100); if (percent - lastPercent >= showPercent) { lastPercent = percent; JCommander.getConsole().println("\tPushing topics to zanata " + percent + "% Done"); } final SpecTopic specTopic = topicEntry.getValue(); // Find the matching translated CSNode and if one can't be found then produce an error. final TranslatedCSNodeWrapper translatedCSNode = findTopicTranslatedCSNode(translatedContentSpec, specTopic); if (translatedCSNode == null) { final TopicWrapper topic = (TopicWrapper) specTopic.getTopic(); messages.get(MessageType.ERROR).add( "Topic ID " + topic.getId() + ", Revision " + topic.getRevision() + " failed to be created in Zanata."); error = true; } else { if (!pushTopicToZanata(providerFactory, contentSpec, specTopic, translatedCSNode, zanataInterface, messages, entities)) { error = true; } } } } } // Print the info/error messages if (messages.size() > 0) { JCommander.getConsole().println("Output:"); // Print the warning messages first and then any errors if (messages.containsKey(MessageType.WARNING)) { JCommander.getConsole().println("Warnings:"); for (final String message : messages.get(MessageType.WARNING)) { JCommander.getConsole().println("\t" + message); } } if (messages.containsKey(MessageType.ERROR)) { JCommander.getConsole().println("Errors:"); for (final String message : messages.get(MessageType.ERROR)) { JCommander.getConsole().println("\t" + message); } } } return !error; }
diff --git a/test/src/com/redhat/ceylon/compiler/java/test/CompilerTest.java b/test/src/com/redhat/ceylon/compiler/java/test/CompilerTest.java index 1fd7a315f..d9806ac5c 100755 --- a/test/src/com/redhat/ceylon/compiler/java/test/CompilerTest.java +++ b/test/src/com/redhat/ceylon/compiler/java/test/CompilerTest.java @@ -1,528 +1,529 @@ /* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License version 2. * * This particular file is subject to the "Classpath" exception as provided in the * LICENSE file that accompanied this code. * * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License, * along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package com.redhat.ceylon.compiler.java.test; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.TreeSet; import java.util.jar.JarFile; import java.util.regex.Matcher; import javax.tools.Diagnostic; import javax.tools.DiagnosticListener; import javax.tools.FileObject; import javax.tools.JavaFileObject; import junit.framework.Assert; import org.junit.Before; import com.redhat.ceylon.compiler.java.codegen.AbstractTransformer; import com.redhat.ceylon.compiler.java.codegen.JavaPositionsRetriever; import com.redhat.ceylon.compiler.java.tools.CeyloncFileManager; import com.redhat.ceylon.compiler.java.tools.CeyloncTaskImpl; import com.redhat.ceylon.compiler.java.tools.CeyloncTool; import com.redhat.ceylon.compiler.java.util.RepositoryLister; import com.redhat.ceylon.compiler.java.util.Util; import com.sun.source.util.TaskEvent; import com.sun.source.util.TaskEvent.Kind; import com.sun.source.util.TaskListener; import com.sun.tools.javac.file.ZipFileIndexCache; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; public abstract class CompilerTest { protected final static String dir = "test/src"; protected final static String destDirGeneral = "build/test-cars"; protected final String destDir; protected final String moduleName; protected final List<String> defaultOptions; public CompilerTest() { // for comparing with java source Package pakage = getClass().getPackage(); moduleName = pakage.getName(); int lastDot = moduleName.lastIndexOf('.'); if(lastDot == -1){ destDir = destDirGeneral + File.separator + transformDestDir(moduleName); } else { destDir = destDirGeneral + File.separator + transformDestDir(moduleName.substring(lastDot+1)); } defaultOptions = Arrays.asList("-out", destDir, "-rep", destDir); } // for subclassers protected String transformDestDir(String name) { return name; } protected CeyloncTool makeCompiler(){ try { return new CeyloncTool(); } catch (VerifyError e) { System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?"); throw e; } } protected String getPackagePath() { Package pakage = getClass().getPackage(); String pkg = pakage == null ? "" : moduleName.replaceAll("\\.", Matcher.quoteReplacement(File.separator)); return dir + File.separator + pkg + File.separator; } protected CeyloncFileManager makeFileManager(CeyloncTool compiler, DiagnosticListener<? super FileObject> diagnosticListener){ return (CeyloncFileManager)compiler.getStandardFileManager(diagnosticListener, null, null); } protected void compareWithJavaSource(String name) { compareWithJavaSource(name+".src", name+".ceylon"); } @Before public void cleanCars() { cleanCars(destDir); } public void cleanCars(String repo) { File destFile = new File(repo); List<String> extensionsToDelete = Arrays.asList(""); new RepositoryLister(extensionsToDelete).list(destFile, new RepositoryLister.Actions() { @Override public void doWithFile(File path) { path.delete(); } public void exitDirectory(File path) { if (path.list().length == 0) { path.delete(); } } }); } protected void assertErrors(String ceylon, CompilerError... expectedErrors) { // make a compiler task // FIXME: runFileManager.setSourcePath(dir); ErrorCollector collector = new ErrorCollector(); CeyloncTaskImpl task = getCompilerTask(defaultOptions, collector, new String[] {ceylon+".ceylon"}); // now compile it all the way Boolean success = task.call(); Assert.assertFalse("Compilation succeeded", success); TreeSet<CompilerError> actualErrors = collector.get(Diagnostic.Kind.ERROR); compareErrors(actualErrors, expectedErrors); } protected void compareErrors(TreeSet<CompilerError> actualErrors, CompilerError... expectedErrors) { TreeSet<CompilerError> expectedErrorSet = new TreeSet<CompilerError>(Arrays.asList(expectedErrors)); // shortcut for simple cases if(expectedErrorSet.size() == 1 && actualErrors.size() == 1){ Assert.assertEquals("Error mismatch", expectedErrorSet.first().toString(), actualErrors.first().toString()); }else{ // first dump the actual errors for(CompilerError actualError : actualErrors){ System.err.println(actualError.lineNumber+": "+actualError.message); } // make sure we have all those we expect for(CompilerError expectedError : expectedErrorSet){ Assert.assertTrue("Missing expected error: "+expectedError, actualErrors.contains(expectedError)); } // make sure we don't have unexpected ones for(CompilerError actualError : actualErrors){ Assert.assertTrue("Unexpected error: "+actualError, expectedErrorSet.contains(actualError)); } } } protected void compareWithJavaSourceWithPositions(String name) { // make a compiler task // FIXME: runFileManager.setSourcePath(dir); CeyloncTaskImpl task = getCompilerTask(new String[] {name+".ceylon"}); // grab the CU after we've completed it class Listener implements TaskListener{ JCCompilationUnit compilationUnit; private String compilerSrc; private JavaPositionsRetriever javaPositionsRetriever = new JavaPositionsRetriever(); @Override public void started(TaskEvent e) { AbstractTransformer.trackNodePositions(javaPositionsRetriever); } @Override public void finished(TaskEvent e) { if(e.getKind() == Kind.ENTER){ if(compilationUnit == null) { compilationUnit = (JCCompilationUnit) e.getCompilationUnit(); // for some reason compilationUnit is full here in the listener, but empty as soon // as the compile task is done. probably to clean up for the gc? javaPositionsRetriever.retrieve(compilationUnit); compilerSrc = normalizeLineEndings(javaPositionsRetriever.getJavaSourceCodeWithCeylonPositions()); AbstractTransformer.trackNodePositions(null); } } } } Listener listener = new Listener(); task.setTaskListener(listener); // now compile it all the way Boolean success = task.call(); Assert.assertTrue("Compilation failed", success); // now look at what we expected String expectedSrc = normalizeLineEndings(readFile(new File(getPackagePath(), name+".src"))).trim(); String compiledSrc = listener.compilerSrc.trim(); Assert.assertEquals("Source code differs", expectedSrc, compiledSrc); } protected void compareWithJavaSourceWithLines(String name) { // make a compiler task // FIXME: runFileManager.setSourcePath(dir); CeyloncTaskImpl task = getCompilerTask(new String[] {name+".ceylon"}); // grab the CU after we've completed it class Listener implements TaskListener{ JCCompilationUnit compilationUnit; private String compilerSrc; private JavaPositionsRetriever javaPositionsRetriever = new JavaPositionsRetriever(); @Override public void started(TaskEvent e) { } @Override public void finished(TaskEvent e) { if(e.getKind() == Kind.ENTER){ if(compilationUnit == null) { compilationUnit = (JCCompilationUnit) e.getCompilationUnit(); // for some reason compilationUnit is full here in the listener, but empty as soon // as the compile task is done. probably to clean up for the gc? javaPositionsRetriever.retrieve(compilationUnit); compilerSrc = normalizeLineEndings(javaPositionsRetriever.getJavaSourceCodeWithCeylonLines()); AbstractTransformer.trackNodePositions(null); } } } } Listener listener = new Listener(); task.setTaskListener(listener); // now compile it all the way Boolean success = task.call(); Assert.assertTrue("Compilation failed", success); // now look at what we expected String expectedSrc = normalizeLineEndings(readFile(new File(getPackagePath(), name+".src"))).trim(); String compiledSrc = listener.compilerSrc.trim(); Assert.assertEquals("Source code differs", expectedSrc, compiledSrc); } protected void compareWithJavaSource(String java, String... ceylon) { // make a compiler task // FIXME: runFileManager.setSourcePath(dir); CeyloncTaskImpl task = getCompilerTask(ceylon); // grab the CU after we've completed it class Listener implements TaskListener{ JCCompilationUnit compilationUnit; private String compilerSrc; @Override public void started(TaskEvent e) { } @Override public void finished(TaskEvent e) { if(e.getKind() == Kind.ENTER){ if(compilationUnit == null) { compilationUnit = (JCCompilationUnit) e.getCompilationUnit(); // for some reason compilationUnit is full here in the listener, but empty as soon // as the compile task is done. probably to clean up for the gc? compilerSrc = normalizeLineEndings(compilationUnit.toString()); } } } } Listener listener = new Listener(); task.setTaskListener(listener); // now compile it all the way Boolean success = task.call(); Assert.assertTrue("Compilation failed", success); // now look at what we expected File expectedSrcFile = new File(getPackagePath(), java); String expectedSrc = normalizeLineEndings(readFile(expectedSrcFile)).trim(); String compiledSrc = listener.compilerSrc.trim(); // THIS IS FOR INTERNAL USE ONLY!!! // Can be used to do batch updating of known correct tests // Uncomment only when you know what you're doing! - //if (expectedSrc != null && compiledSrc != null && !expectedSrc.equals(compiledSrc)) { - // writeFile(expectedSrcFile, compiledSrc); - //} +// if (expectedSrc != null && compiledSrc != null && !expectedSrc.equals(compiledSrc)) { +// writeFile(expectedSrcFile, compiledSrc); +// expectedSrc = compiledSrc; +// } Assert.assertEquals("Source code differs", expectedSrc, compiledSrc); } private String readFile(File file) { try{ Reader reader = new FileReader(file); StringBuilder strbuf = new StringBuilder(); try{ char[] buf = new char[1024]; int read; while((read = reader.read(buf)) > -1) strbuf.append(buf, 0, read); }finally{ reader.close(); } return strbuf.toString(); }catch(IOException x){ throw new RuntimeException(x); } } // THIS IS FOR INTERNAL USE ONLY!!! private void writeFile(File file, String src) { try{ Writer writer = new FileWriter(file); try{ writer.write(src); }finally{ writer.close(); } }catch(IOException x){ throw new RuntimeException(x); } } private String normalizeLineEndings(String txt) { String result = txt.replaceAll("\r\n", "\n"); // Windows result = result.replaceAll("\r", "\n"); // Mac (OS<=9) return result; } protected void compile(String... ceylon) { Boolean success = getCompilerTask(ceylon).call(); Assert.assertTrue(success); } protected void compilesWithoutWarnings(String... ceylon) { ErrorCollector dl = new ErrorCollector(); Boolean success = getCompilerTask(defaultOptions, dl, ceylon).call(); Assert.assertTrue(success); Assert.assertEquals("The code compiled with javac warnings", 0, dl.get(Diagnostic.Kind.WARNING).size() + dl.get(Diagnostic.Kind.MANDATORY_WARNING).size()); } protected void compileAndRun(String main, String... ceylon) { compile(ceylon); run(main); } protected void run(String main) { File car = new File(getDestCar()); run(main, car); } protected void run(String main, File... cars) { try{ // make sure we load the stuff from the Car @SuppressWarnings("deprecation") List<URL> urls = new ArrayList<URL>(cars.length); for (File car : cars) { Assert.assertTrue("Car exists", car.exists()); URL url = car.toURL(); urls.add(url); } System.err.println("Running " + main +" with classpath" + urls); NonCachingURLClassLoader loader = new NonCachingURLClassLoader(urls.toArray(new URL[urls.size()])); String mainClass = main; String mainMethod = main.replaceAll("^.*\\.", ""); if (Util.isInitialLowerCase(mainMethod)) { mainClass = main + "_"; } java.lang.Class<?> klass = java.lang.Class.forName(mainClass, true, loader); if (Util.isInitialLowerCase(mainMethod)) { // A main method Method m = klass.getDeclaredMethod(mainMethod); m.setAccessible(true); m.invoke(null); } else { // A main class final Constructor<?> ctor = klass.getDeclaredConstructor(); ctor.setAccessible(true); ctor.newInstance(); } loader.clearCache(); }catch(Exception x){ throw new RuntimeException(x); } } public static class NonCachingURLClassLoader extends URLClassLoader { public NonCachingURLClassLoader(URL[] urls) { super(urls); } public void clearCache() { try { Class<?> klass = java.net.URLClassLoader.class; Field ucp = klass.getDeclaredField("ucp"); ucp.setAccessible(true); Object sunMiscURLClassPath = ucp.get(this); Field loaders = sunMiscURLClassPath.getClass().getDeclaredField("loaders"); loaders.setAccessible(true); Object collection = loaders.get(sunMiscURLClassPath); for (Object sunMiscURLClassPathJarLoader : ((Collection<?>) collection).toArray()) { try { Field loader = sunMiscURLClassPathJarLoader.getClass().getDeclaredField("jar"); loader.setAccessible(true); Object jarFile = loader.get(sunMiscURLClassPathJarLoader); ((JarFile) jarFile).close(); } catch (Throwable t) { // not a JAR loader? t.printStackTrace(); } } } catch (Throwable t) { // Something's wrong t.printStackTrace(); } return; } } protected CeyloncTaskImpl getCompilerTask(String... sourcePaths){ return getCompilerTask(defaultOptions, null, sourcePaths); } protected CeyloncTaskImpl getCompilerTask(List<String> options, String... sourcePaths){ return getCompilerTask(options, null, sourcePaths); } protected CeyloncTaskImpl getCompilerTask(List<String> options, DiagnosticListener<? super FileObject> diagnosticListener, String... sourcePaths){ return getCompilerTask(options, diagnosticListener, null, sourcePaths); } protected CeyloncTaskImpl getCompilerTask(List<String> initialOptions, DiagnosticListener<? super FileObject> diagnosticListener, List<String> modules, String... sourcePaths){ // make sure we get a fresh jar cache for each compiler run // FIXME: make this only get rid of the jars we produce, to win 2s out of 17s ZipFileIndexCache.getSharedInstance().clearCache(); java.util.List<File> sourceFiles = new ArrayList<File>(sourcePaths.length); for(String file : sourcePaths){ sourceFiles.add(new File(getPackagePath(), file)); } CeyloncTool runCompiler = makeCompiler(); CeyloncFileManager runFileManager = makeFileManager(runCompiler, diagnosticListener); // make sure the destination repo exists new File(destDir).mkdirs(); List<String> options = new LinkedList<String>(); options.addAll(initialOptions); if(!options.contains("-src")) options.addAll(Arrays.asList("-src", getSourcePath())); boolean hasVerbose = false; for(String option : options){ if(option.startsWith("-verbose")){ hasVerbose = true; break; } } if(!hasVerbose) options.add("-verbose:ast,code"); Iterable<? extends JavaFileObject> compilationUnits1 = runFileManager.getJavaFileObjectsFromFiles(sourceFiles); return (CeyloncTaskImpl) runCompiler.getTask(null, runFileManager, diagnosticListener, options, modules, compilationUnits1); } protected String getSourcePath() { return dir; } protected String getDestCar() { return getModuleArchive("default", null).getPath(); } protected File getModuleArchive(String moduleName, String version) { return getModuleArchive(moduleName, version, destDir); } protected static File getModuleArchive(String moduleName, String version, String destDir) { return getArchiveName(moduleName, version, destDir, "car"); } protected File getSourceArchive(String moduleName, String version) { return getArchiveName(moduleName, version, destDir, "src"); } protected static File getSourceArchive(String moduleName, String version, String destDir) { return getArchiveName(moduleName, version, destDir, "src"); } protected static File getArchiveName(String moduleName, String version, String destDir, String extension) { String modulePath = moduleName.replace('.', File.separatorChar); if(version != null) modulePath += File.separatorChar+version; modulePath += File.separator; String artifactName = modulePath+moduleName; if(version != null) artifactName += "-"+version; artifactName += "."+extension; File archiveFile = new File(destDir, artifactName); return archiveFile; } }
true
true
protected void compareWithJavaSource(String java, String... ceylon) { // make a compiler task // FIXME: runFileManager.setSourcePath(dir); CeyloncTaskImpl task = getCompilerTask(ceylon); // grab the CU after we've completed it class Listener implements TaskListener{ JCCompilationUnit compilationUnit; private String compilerSrc; @Override public void started(TaskEvent e) { } @Override public void finished(TaskEvent e) { if(e.getKind() == Kind.ENTER){ if(compilationUnit == null) { compilationUnit = (JCCompilationUnit) e.getCompilationUnit(); // for some reason compilationUnit is full here in the listener, but empty as soon // as the compile task is done. probably to clean up for the gc? compilerSrc = normalizeLineEndings(compilationUnit.toString()); } } } } Listener listener = new Listener(); task.setTaskListener(listener); // now compile it all the way Boolean success = task.call(); Assert.assertTrue("Compilation failed", success); // now look at what we expected File expectedSrcFile = new File(getPackagePath(), java); String expectedSrc = normalizeLineEndings(readFile(expectedSrcFile)).trim(); String compiledSrc = listener.compilerSrc.trim(); // THIS IS FOR INTERNAL USE ONLY!!! // Can be used to do batch updating of known correct tests // Uncomment only when you know what you're doing! //if (expectedSrc != null && compiledSrc != null && !expectedSrc.equals(compiledSrc)) { // writeFile(expectedSrcFile, compiledSrc); //} Assert.assertEquals("Source code differs", expectedSrc, compiledSrc); }
protected void compareWithJavaSource(String java, String... ceylon) { // make a compiler task // FIXME: runFileManager.setSourcePath(dir); CeyloncTaskImpl task = getCompilerTask(ceylon); // grab the CU after we've completed it class Listener implements TaskListener{ JCCompilationUnit compilationUnit; private String compilerSrc; @Override public void started(TaskEvent e) { } @Override public void finished(TaskEvent e) { if(e.getKind() == Kind.ENTER){ if(compilationUnit == null) { compilationUnit = (JCCompilationUnit) e.getCompilationUnit(); // for some reason compilationUnit is full here in the listener, but empty as soon // as the compile task is done. probably to clean up for the gc? compilerSrc = normalizeLineEndings(compilationUnit.toString()); } } } } Listener listener = new Listener(); task.setTaskListener(listener); // now compile it all the way Boolean success = task.call(); Assert.assertTrue("Compilation failed", success); // now look at what we expected File expectedSrcFile = new File(getPackagePath(), java); String expectedSrc = normalizeLineEndings(readFile(expectedSrcFile)).trim(); String compiledSrc = listener.compilerSrc.trim(); // THIS IS FOR INTERNAL USE ONLY!!! // Can be used to do batch updating of known correct tests // Uncomment only when you know what you're doing! // if (expectedSrc != null && compiledSrc != null && !expectedSrc.equals(compiledSrc)) { // writeFile(expectedSrcFile, compiledSrc); // expectedSrc = compiledSrc; // } Assert.assertEquals("Source code differs", expectedSrc, compiledSrc); }
diff --git a/sakai-plugin/src/main/java/org/sakaiproject/maven/plugin/component/ComponentDeployMojo.java b/sakai-plugin/src/main/java/org/sakaiproject/maven/plugin/component/ComponentDeployMojo.java index 631b0b5..17f7945 100644 --- a/sakai-plugin/src/main/java/org/sakaiproject/maven/plugin/component/ComponentDeployMojo.java +++ b/sakai-plugin/src/main/java/org/sakaiproject/maven/plugin/component/ComponentDeployMojo.java @@ -1,445 +1,445 @@ package org.sakaiproject.maven.plugin.component; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.Properties; import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.AbstractArtifactResolutionException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.codehaus.plexus.archiver.manager.NoSuchArchiverException; /** * Generate the exploded webapp * * @goal deploy * @requiresDependencyResolution runtime */ public class ComponentDeployMojo extends AbstractComponentMojo { /** * The directory where the webapp is built. * * @parameter expression="${maven.tomcat.home}/components/${project.build.finalName}" * @required */ private File deployDirectory; /** * A map to define the destination where items are unpacked. * * @parameter expression="${sakai.app.server}" */ private String appServer = null; /** * The ID of the artifact to use when deploying. * * @parameter expression="${project.artifactId}" * @required */ private String deployId = null; private Properties locationMap; private static Properties defaultLocatioMap; static { defaultLocatioMap = new Properties(); defaultLocatioMap.setProperty("components", "components/"); defaultLocatioMap.setProperty("webapps", "webapps/"); defaultLocatioMap.setProperty("shared/lib", "shared/lib/"); defaultLocatioMap.setProperty("server/lib", "server/lib/"); defaultLocatioMap.setProperty("common/lib", "common/lib/"); defaultLocatioMap.setProperty("configuration", "/"); } public File getDeployDirectory() { return deployDirectory; } public void setDeployDirectory(File deployDirectory) { this.deployDirectory = deployDirectory; } public String getAppServer() { return appServer; } public void setAppServer(String appServer) { this.appServer = appServer; } public String getDeployId() { return deployId; } public void setDeployId(String deployId) { this.deployId = deployId; } public void execute() throws MojoExecutionException, MojoFailureException { deployToContainer(); } public void deployToContainer() throws MojoExecutionException, MojoFailureException { try { Set artifacts = project.getDependencyArtifacts(); // iterate through the this to extract dependencies and deploy String packaging = project.getPackaging(); File deployDir = getDeployDirectory(); if (deployDir == null) { throw new MojoFailureException( "deployDirectory has not been set"); } if ("sakai-component".equals(packaging)) { // UseCase: Sakai component in a pom // deploy to component and unpack as a getLog().info( "Deploying " + project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getPackaging() + " as an unpacked component"); File destination = new File(deployDir, getDeploySubDir("components")); String fileName = project.getArtifactId(); File destinationDir = new File(destination, fileName); Artifact artifact = project.getArtifact(); if (artifact == null) { getLog().error( "No Artifact found in project " + getProjectId()); throw new MojoFailureException( "No Artifact found in project"); } File artifactFile = artifact.getFile(); if (artifactFile == null) { artifactResolver.resolve(artifact, remoteRepositories, artifactRepository); artifactFile = artifact.getFile(); } if (artifactFile == null) { getLog().error( "Artifact File is null for " + getProjectId()); throw new MojoFailureException("Artifact File is null "); } getLog().info( "Unpacking " + artifactFile + " to " + destinationDir); deleteAll(destinationDir); destinationDir.mkdirs(); unpack(artifactFile, destinationDir, "war", false); } else if ("sakai-configuration".equals(packaging)) { // UseCase: Sakai configuration in a pom // deploy to component and unpack as a getLog().info( "Deploying " + project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getPackaging() + " as an unpacked configuration"); File destinationDir = new File(deployDir, getDeploySubDir("configuration")); Artifact artifact = project.getArtifact(); if (artifact == null) { getLog().error( "No Artifact found in project " + getProjectId()); throw new MojoFailureException( "No Artifact found in project"); } File artifactFile = artifact.getFile(); if (artifactFile == null) { artifactResolver.resolve(artifact, remoteRepositories, artifactRepository); artifactFile = artifact.getFile(); } if (artifactFile == null) { getLog().error( "Artifact File is null for " + getProjectId()); throw new MojoFailureException("Artifact File is null "); } getLog().info( "Unpacking " + artifactFile + " to " + destinationDir); destinationDir.mkdirs(); // we use a zip unarchiver unpack(artifactFile, destinationDir, "zip" , false); } else if ("war".equals(packaging)) { // UseCase: war webapp // deploy to webapps but dont unpack getLog().info( "Deploying " + project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getPackaging() + " as a webapp"); deployProjectArtifact(new File(deployDir, getDeploySubDir("webapps")), false, true); } else if ("jar".equals(packaging)) { // UseCase: jar, marked with a property // deploy the target Properties p = project.getProperties(); String deployTarget = p.getProperty("deploy.target"); if ("shared".equals(deployTarget)) { deployProjectArtifact(new File(deployDir, getDeploySubDir("shared/lib")), true, false); } else if ("common".equals(deployTarget)) { deployProjectArtifact(new File(deployDir, getDeploySubDir("common/lib")), true, false); } else if ("server".equals(deployTarget)) { deployProjectArtifact(new File(deployDir, getDeploySubDir("server/lib")), true, false); } else { getLog().info( "No deployment specification -- skipping " + getProjectId()); } } else if ("pom".equals(packaging)) { // UseCase: pom, marked with a property // deploy the contents Properties p = project.getProperties(); String deployTarget = p.getProperty("deploy.target"); if ("shared".equals(deployTarget)) { File destinationDir = new File(deployDir, getDeploySubDir("shared/lib")); destinationDir.mkdirs(); deployArtifacts(artifacts, destinationDir); } else if ("common".equals(deployTarget)) { File destinationDir = new File(deployDir, getDeploySubDir("common/lib")); destinationDir.mkdirs(); deployArtifacts(artifacts, destinationDir); } else if ("server".equals(deployTarget)) { File destinationDir = new File(deployDir, getDeploySubDir("server/lib")); destinationDir.mkdirs(); deployArtifacts(artifacts, destinationDir); } else if ( "tomcat-overlay".equals(deployTarget)) { String cleanTargetPaths = p.getProperty("clean.targets"); String[] cleanPaths = cleanTargetPaths.split(";"); for ( String pathToClean : cleanPaths ) { File destinationDir = new File(deployDir, getDeploySubDir(pathToClean)); getLog().info("Deleting "+destinationDir); deleteAll(destinationDir); } deployDir.mkdirs(); deployOverlay(artifacts, deployDir); } else { getLog().info( "No deployment specification -- skipping " + getProjectId()); } } else { getLog().info( "No deployment specification -- skipping " + getProjectId()); } } catch (IOException ex) { getLog().debug("Failed to deploy to container ", ex); - throw new MojoFailureException("Fialed to deploy to container :" + throw new MojoFailureException("Failed to deploy to container :" + ex.getMessage()); } catch (NoSuchArchiverException ex) { getLog().debug("Failed to deploy to container ", ex); - throw new MojoFailureException("Fialed to deploy to container :" + throw new MojoFailureException("Failed to deploy to container :" + ex.getMessage()); } catch (AbstractArtifactResolutionException ex) { getLog().debug("Failed to deploy to container ", ex); - throw new MojoFailureException("Fialed to deploy to container :" + throw new MojoFailureException("Failed to deploy to container :" + ex.getMessage()); } } /** * @param string * @param string2 * @return */ private String getDeploySubDir(String key) { if ( locationMap == null ) { if ( appServer != null ) { try { InputStream in = getClass().getClassLoader().getResourceAsStream( "deploy." + appServer + ".properties"); Properties p = new Properties(); p.load(in); in.close(); locationMap = p; } catch (Exception ex) { this.getLog().warn("No Config for appserver "+appServer+" cause:"+ex.getMessage()); } } if ( locationMap == null ) { locationMap = defaultLocatioMap; } } String deploySubDir = locationMap.getProperty(key); if ( deploySubDir == null || deploySubDir.trim().length() == 0 ) { deploySubDir = defaultLocatioMap.getProperty(key); } if (deploySubDir == null ) { deploySubDir = key; } if ( !deploySubDir.endsWith("/") ) { deploySubDir = deploySubDir + "/"; } return deploySubDir; } protected void deployOverlay(Set artifacts, File destination) throws IOException, MojoFailureException, AbstractArtifactResolutionException, MojoExecutionException, NoSuchArchiverException { for (Iterator iter = artifacts.iterator(); iter.hasNext();) { Artifact artifact = (Artifact) iter.next(); if (artifact == null) { getLog().error( "Null Artifact found, sould never happen, in artifacts for project " + getProjectId()); throw new MojoFailureException( "Null Artifact found, sould never happen, in artifacts for project "); } File artifactFile = artifact.getFile(); if (artifactFile == null) { artifactResolver.resolve(artifact, remoteRepositories, artifactRepository); artifactFile = artifact.getFile(); } if (artifactFile == null) { getLog().error( "Artifact File is null for dependency " + artifact.getId() + " in " + getProjectId()); throw new MojoFailureException( "Artifact File is null for dependency " + artifact.getId() + " in " + getProjectId()); } getLog().debug("Processing: " + artifact.getId()); if ( !"test".equals(artifact.getScope()) ) { unpack(artifact.getFile(), destination, artifact.getType(),true); } } } protected void deployArtifacts(Set artifacts, File destination) throws IOException, MojoFailureException, AbstractArtifactResolutionException { for (Iterator iter = artifacts.iterator(); iter.hasNext();) { Artifact artifact = (Artifact) iter.next(); if (artifact == null) { getLog().error( "Null Artifact found, sould never happen, in artifacts for project " + getProjectId()); throw new MojoFailureException( "Null Artifact found, sould never happen, in artifacts for project "); } File artifactFile = artifact.getFile(); if (artifactFile == null) { artifactResolver.resolve(artifact, remoteRepositories, artifactRepository); artifactFile = artifact.getFile(); } if (artifactFile == null) { getLog().error( "Artifact File is null for dependency " + artifact.getId() + " in " + getProjectId()); throw new MojoFailureException( "Artifact File is null for dependency " + artifact.getId() + " in " + getProjectId()); } String targetFileName = getDefaultFinalName(artifact); getLog().debug("Processing: " + targetFileName); File destinationFile = new File(destination, targetFileName); if ("provided".equals(artifact.getScope()) || "test".equals(artifact.getScope())) { getLog().info( "Skipping " + artifactFile + " Scope " + artifact.getScope()); } else { getLog() .info("Copy " + artifactFile + " to " + destinationFile); copyFileIfModified(artifact.getFile(), destinationFile); } } } private void deployProjectArtifact(File destination, boolean withVersion, boolean deleteStub) throws MojoFailureException, IOException, AbstractArtifactResolutionException { Artifact artifact = project.getArtifact(); String fileName = null; String stubName = null; if (withVersion) { fileName = getDeployId() + "-" + project.getVersion() + "." + project.getPackaging(); stubName = getDeployId() + "-" + project.getVersion(); } else { fileName = getDeployId() + "." + project.getPackaging(); stubName = getDeployId(); } File destinationFile = new File(destination, fileName); File stubFile = new File(destination, stubName); Set artifacts = project.getArtifacts(); getLog().info("Found " + artifacts.size() + " artifacts"); for (Iterator i = artifacts.iterator(); i.hasNext();) { Artifact a = (Artifact) i.next(); getLog() .info( "Artifact Id " + a.getArtifactId() + " file " + a.getFile()); } if (artifact == null) { getLog().error("No Artifact found in project " + getProjectId()); throw new MojoFailureException( "No Artifact found in project, target was " + destinationFile); } File artifactFile = artifact.getFile(); if (artifactFile == null) { artifactResolver.resolve(artifact, remoteRepositories, artifactRepository); artifactFile = artifact.getFile(); } if (artifactFile == null) { getLog().error( "Artifact File is null for " + getProjectId() + ", target was " + destinationFile); throw new MojoFailureException("Artifact File is null "); } getLog().info("Copy " + artifactFile + " to " + destinationFile); destinationFile.getParentFile().mkdirs(); if (deleteStub && stubFile.exists()) { deleteAll(stubFile); } copyFileIfModified(artifactFile, destinationFile); } }
false
true
public void deployToContainer() throws MojoExecutionException, MojoFailureException { try { Set artifacts = project.getDependencyArtifacts(); // iterate through the this to extract dependencies and deploy String packaging = project.getPackaging(); File deployDir = getDeployDirectory(); if (deployDir == null) { throw new MojoFailureException( "deployDirectory has not been set"); } if ("sakai-component".equals(packaging)) { // UseCase: Sakai component in a pom // deploy to component and unpack as a getLog().info( "Deploying " + project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getPackaging() + " as an unpacked component"); File destination = new File(deployDir, getDeploySubDir("components")); String fileName = project.getArtifactId(); File destinationDir = new File(destination, fileName); Artifact artifact = project.getArtifact(); if (artifact == null) { getLog().error( "No Artifact found in project " + getProjectId()); throw new MojoFailureException( "No Artifact found in project"); } File artifactFile = artifact.getFile(); if (artifactFile == null) { artifactResolver.resolve(artifact, remoteRepositories, artifactRepository); artifactFile = artifact.getFile(); } if (artifactFile == null) { getLog().error( "Artifact File is null for " + getProjectId()); throw new MojoFailureException("Artifact File is null "); } getLog().info( "Unpacking " + artifactFile + " to " + destinationDir); deleteAll(destinationDir); destinationDir.mkdirs(); unpack(artifactFile, destinationDir, "war", false); } else if ("sakai-configuration".equals(packaging)) { // UseCase: Sakai configuration in a pom // deploy to component and unpack as a getLog().info( "Deploying " + project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getPackaging() + " as an unpacked configuration"); File destinationDir = new File(deployDir, getDeploySubDir("configuration")); Artifact artifact = project.getArtifact(); if (artifact == null) { getLog().error( "No Artifact found in project " + getProjectId()); throw new MojoFailureException( "No Artifact found in project"); } File artifactFile = artifact.getFile(); if (artifactFile == null) { artifactResolver.resolve(artifact, remoteRepositories, artifactRepository); artifactFile = artifact.getFile(); } if (artifactFile == null) { getLog().error( "Artifact File is null for " + getProjectId()); throw new MojoFailureException("Artifact File is null "); } getLog().info( "Unpacking " + artifactFile + " to " + destinationDir); destinationDir.mkdirs(); // we use a zip unarchiver unpack(artifactFile, destinationDir, "zip" , false); } else if ("war".equals(packaging)) { // UseCase: war webapp // deploy to webapps but dont unpack getLog().info( "Deploying " + project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getPackaging() + " as a webapp"); deployProjectArtifact(new File(deployDir, getDeploySubDir("webapps")), false, true); } else if ("jar".equals(packaging)) { // UseCase: jar, marked with a property // deploy the target Properties p = project.getProperties(); String deployTarget = p.getProperty("deploy.target"); if ("shared".equals(deployTarget)) { deployProjectArtifact(new File(deployDir, getDeploySubDir("shared/lib")), true, false); } else if ("common".equals(deployTarget)) { deployProjectArtifact(new File(deployDir, getDeploySubDir("common/lib")), true, false); } else if ("server".equals(deployTarget)) { deployProjectArtifact(new File(deployDir, getDeploySubDir("server/lib")), true, false); } else { getLog().info( "No deployment specification -- skipping " + getProjectId()); } } else if ("pom".equals(packaging)) { // UseCase: pom, marked with a property // deploy the contents Properties p = project.getProperties(); String deployTarget = p.getProperty("deploy.target"); if ("shared".equals(deployTarget)) { File destinationDir = new File(deployDir, getDeploySubDir("shared/lib")); destinationDir.mkdirs(); deployArtifacts(artifacts, destinationDir); } else if ("common".equals(deployTarget)) { File destinationDir = new File(deployDir, getDeploySubDir("common/lib")); destinationDir.mkdirs(); deployArtifacts(artifacts, destinationDir); } else if ("server".equals(deployTarget)) { File destinationDir = new File(deployDir, getDeploySubDir("server/lib")); destinationDir.mkdirs(); deployArtifacts(artifacts, destinationDir); } else if ( "tomcat-overlay".equals(deployTarget)) { String cleanTargetPaths = p.getProperty("clean.targets"); String[] cleanPaths = cleanTargetPaths.split(";"); for ( String pathToClean : cleanPaths ) { File destinationDir = new File(deployDir, getDeploySubDir(pathToClean)); getLog().info("Deleting "+destinationDir); deleteAll(destinationDir); } deployDir.mkdirs(); deployOverlay(artifacts, deployDir); } else { getLog().info( "No deployment specification -- skipping " + getProjectId()); } } else { getLog().info( "No deployment specification -- skipping " + getProjectId()); } } catch (IOException ex) { getLog().debug("Failed to deploy to container ", ex); throw new MojoFailureException("Fialed to deploy to container :" + ex.getMessage()); } catch (NoSuchArchiverException ex) { getLog().debug("Failed to deploy to container ", ex); throw new MojoFailureException("Fialed to deploy to container :" + ex.getMessage()); } catch (AbstractArtifactResolutionException ex) { getLog().debug("Failed to deploy to container ", ex); throw new MojoFailureException("Fialed to deploy to container :" + ex.getMessage()); } }
public void deployToContainer() throws MojoExecutionException, MojoFailureException { try { Set artifacts = project.getDependencyArtifacts(); // iterate through the this to extract dependencies and deploy String packaging = project.getPackaging(); File deployDir = getDeployDirectory(); if (deployDir == null) { throw new MojoFailureException( "deployDirectory has not been set"); } if ("sakai-component".equals(packaging)) { // UseCase: Sakai component in a pom // deploy to component and unpack as a getLog().info( "Deploying " + project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getPackaging() + " as an unpacked component"); File destination = new File(deployDir, getDeploySubDir("components")); String fileName = project.getArtifactId(); File destinationDir = new File(destination, fileName); Artifact artifact = project.getArtifact(); if (artifact == null) { getLog().error( "No Artifact found in project " + getProjectId()); throw new MojoFailureException( "No Artifact found in project"); } File artifactFile = artifact.getFile(); if (artifactFile == null) { artifactResolver.resolve(artifact, remoteRepositories, artifactRepository); artifactFile = artifact.getFile(); } if (artifactFile == null) { getLog().error( "Artifact File is null for " + getProjectId()); throw new MojoFailureException("Artifact File is null "); } getLog().info( "Unpacking " + artifactFile + " to " + destinationDir); deleteAll(destinationDir); destinationDir.mkdirs(); unpack(artifactFile, destinationDir, "war", false); } else if ("sakai-configuration".equals(packaging)) { // UseCase: Sakai configuration in a pom // deploy to component and unpack as a getLog().info( "Deploying " + project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getPackaging() + " as an unpacked configuration"); File destinationDir = new File(deployDir, getDeploySubDir("configuration")); Artifact artifact = project.getArtifact(); if (artifact == null) { getLog().error( "No Artifact found in project " + getProjectId()); throw new MojoFailureException( "No Artifact found in project"); } File artifactFile = artifact.getFile(); if (artifactFile == null) { artifactResolver.resolve(artifact, remoteRepositories, artifactRepository); artifactFile = artifact.getFile(); } if (artifactFile == null) { getLog().error( "Artifact File is null for " + getProjectId()); throw new MojoFailureException("Artifact File is null "); } getLog().info( "Unpacking " + artifactFile + " to " + destinationDir); destinationDir.mkdirs(); // we use a zip unarchiver unpack(artifactFile, destinationDir, "zip" , false); } else if ("war".equals(packaging)) { // UseCase: war webapp // deploy to webapps but dont unpack getLog().info( "Deploying " + project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getPackaging() + " as a webapp"); deployProjectArtifact(new File(deployDir, getDeploySubDir("webapps")), false, true); } else if ("jar".equals(packaging)) { // UseCase: jar, marked with a property // deploy the target Properties p = project.getProperties(); String deployTarget = p.getProperty("deploy.target"); if ("shared".equals(deployTarget)) { deployProjectArtifact(new File(deployDir, getDeploySubDir("shared/lib")), true, false); } else if ("common".equals(deployTarget)) { deployProjectArtifact(new File(deployDir, getDeploySubDir("common/lib")), true, false); } else if ("server".equals(deployTarget)) { deployProjectArtifact(new File(deployDir, getDeploySubDir("server/lib")), true, false); } else { getLog().info( "No deployment specification -- skipping " + getProjectId()); } } else if ("pom".equals(packaging)) { // UseCase: pom, marked with a property // deploy the contents Properties p = project.getProperties(); String deployTarget = p.getProperty("deploy.target"); if ("shared".equals(deployTarget)) { File destinationDir = new File(deployDir, getDeploySubDir("shared/lib")); destinationDir.mkdirs(); deployArtifacts(artifacts, destinationDir); } else if ("common".equals(deployTarget)) { File destinationDir = new File(deployDir, getDeploySubDir("common/lib")); destinationDir.mkdirs(); deployArtifacts(artifacts, destinationDir); } else if ("server".equals(deployTarget)) { File destinationDir = new File(deployDir, getDeploySubDir("server/lib")); destinationDir.mkdirs(); deployArtifacts(artifacts, destinationDir); } else if ( "tomcat-overlay".equals(deployTarget)) { String cleanTargetPaths = p.getProperty("clean.targets"); String[] cleanPaths = cleanTargetPaths.split(";"); for ( String pathToClean : cleanPaths ) { File destinationDir = new File(deployDir, getDeploySubDir(pathToClean)); getLog().info("Deleting "+destinationDir); deleteAll(destinationDir); } deployDir.mkdirs(); deployOverlay(artifacts, deployDir); } else { getLog().info( "No deployment specification -- skipping " + getProjectId()); } } else { getLog().info( "No deployment specification -- skipping " + getProjectId()); } } catch (IOException ex) { getLog().debug("Failed to deploy to container ", ex); throw new MojoFailureException("Failed to deploy to container :" + ex.getMessage()); } catch (NoSuchArchiverException ex) { getLog().debug("Failed to deploy to container ", ex); throw new MojoFailureException("Failed to deploy to container :" + ex.getMessage()); } catch (AbstractArtifactResolutionException ex) { getLog().debug("Failed to deploy to container ", ex); throw new MojoFailureException("Failed to deploy to container :" + ex.getMessage()); } }
diff --git a/gdx/src/com/badlogic/gdx/math/Matrix3.java b/gdx/src/com/badlogic/gdx/math/Matrix3.java index 7903840a4..3dbc2d771 100644 --- a/gdx/src/com/badlogic/gdx/math/Matrix3.java +++ b/gdx/src/com/badlogic/gdx/math/Matrix3.java @@ -1,314 +1,313 @@ /******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.math; import java.io.Serializable; import com.badlogic.gdx.utils.GdxRuntimeException; /** A 3x3 column major matrix for 2D transforms. * * @author mzechner */ public class Matrix3 implements Serializable { private static final long serialVersionUID = 7907569533774959788L; private final static float DEGREE_TO_RAD = (float)Math.PI / 180; public float[] vals = new float[9]; private float[] tmp = new float[9]; public Matrix3 () { idt(); } /** Sets this matrix to the identity matrix * @return this matrix */ public Matrix3 idt () { this.vals[0] = 1; this.vals[1] = 0; this.vals[2] = 0; this.vals[3] = 0; this.vals[4] = 1; this.vals[5] = 0; this.vals[6] = 0; this.vals[7] = 0; this.vals[8] = 1; return this; } /** Multiplies this matrix with the other matrix in the order this * m. * @return this matrix */ public Matrix3 mul (Matrix3 m) { float v00 = vals[0] * m.vals[0] + vals[3] * m.vals[1] + vals[6] * m.vals[2]; float v01 = vals[0] * m.vals[3] + vals[3] * m.vals[4] + vals[6] * m.vals[5]; float v02 = vals[0] * m.vals[6] + vals[3] * m.vals[7] + vals[6] * m.vals[8]; float v10 = vals[1] * m.vals[0] + vals[4] * m.vals[1] + vals[7] * m.vals[2]; float v11 = vals[1] * m.vals[3] + vals[4] * m.vals[4] + vals[7] * m.vals[5]; float v12 = vals[1] * m.vals[6] + vals[4] * m.vals[7] + vals[7] * m.vals[8]; float v20 = vals[2] * m.vals[0] + vals[5] * m.vals[1] + vals[8] * m.vals[2]; float v21 = vals[2] * m.vals[3] + vals[5] * m.vals[4] + vals[8] * m.vals[5]; float v22 = vals[2] * m.vals[6] + vals[5] * m.vals[7] + vals[8] * m.vals[8]; vals[0] = v00; vals[1] = v10; vals[2] = v20; vals[3] = v01; vals[4] = v11; vals[5] = v21; vals[6] = v02; vals[7] = v12; vals[8] = v22; return this; } /** Sets this matrix to a rotation matrix that will rotate any vector in counter clockwise order around the z-axis. * @param angle the angle in degrees. * @return this matrix */ public Matrix3 setToRotation (float angle) { angle = DEGREE_TO_RAD * angle; float cos = (float)Math.cos(angle); float sin = (float)Math.sin(angle); this.vals[0] = cos; this.vals[1] = sin; this.vals[2] = 0; this.vals[3] = -sin; this.vals[4] = cos; this.vals[5] = 0; this.vals[6] = 0; this.vals[7] = 0; this.vals[8] = 1; return this; } /** Sets this matrix to a translation matrix. * @param x the translation in x * @param y the translation in y * @return this matrix */ public Matrix3 setToTranslation (float x, float y) { this.vals[0] = 1; this.vals[1] = 0; this.vals[2] = 0; this.vals[3] = 0; this.vals[4] = 1; this.vals[5] = 0; this.vals[6] = x; this.vals[7] = y; this.vals[8] = 1; return this; } /** Sets this matrix to a scaling matrix * * @param scaleX the scale in x * @param scaleY the scale in y * @return this matrix */ public Matrix3 setToScaling (float scaleX, float scaleY) { this.vals[0] = scaleX; this.vals[1] = 0; this.vals[2] = 0; this.vals[3] = 0; this.vals[4] = scaleY; this.vals[5] = 0; this.vals[6] = 0; this.vals[7] = 0; this.vals[8] = 1; return this; } public String toString () { return "[" + vals[0] + "|" + vals[3] + "|" + vals[6] + "]\n" + "[" + vals[1] + "|" + vals[4] + "|" + vals[7] + "]\n" + "[" + vals[2] + "|" + vals[5] + "|" + vals[8] + "]"; } /** @return the determinant of this matrix */ public float det () { return vals[0] * vals[4] * vals[8] + vals[3] * vals[7] * vals[2] + vals[6] * vals[1] * vals[5] - vals[0] * vals[7] * vals[5] - vals[3] * vals[1] * vals[8] - vals[6] * vals[4] * vals[2]; } /** Inverts this matrix given that the determinant is != 0 * @return this matrix */ public Matrix3 inv () { float det = det(); if (det == 0) throw new GdxRuntimeException("Can't invert a singular matrix"); float inv_det = 1.0f / det; - float tmp[] = {0, 0, 0, 0, 0, 0, 0, 0, 0}; tmp[0] = vals[4] * vals[8] - vals[5] * vals[7]; tmp[1] = vals[2] * vals[7] - vals[1] * vals[8]; tmp[2] = vals[1] * vals[5] - vals[2] * vals[4]; tmp[3] = vals[5] * vals[6] - vals[3] * vals[8]; tmp[4] = vals[0] * vals[8] - vals[2] * vals[6]; tmp[5] = vals[2] * vals[3] - vals[0] * vals[5]; tmp[6] = vals[3] * vals[7] - vals[4] * vals[6]; tmp[7] = vals[1] * vals[6] - vals[0] * vals[7]; tmp[8] = vals[0] * vals[4] - vals[1] * vals[3]; vals[0] = inv_det * tmp[0]; vals[1] = inv_det * tmp[1]; vals[2] = inv_det * tmp[2]; vals[3] = inv_det * tmp[3]; vals[4] = inv_det * tmp[4]; vals[5] = inv_det * tmp[5]; vals[6] = inv_det * tmp[6]; vals[7] = inv_det * tmp[7]; vals[8] = inv_det * tmp[8]; return this; } public Matrix3 set (Matrix3 mat) { vals[0] = mat.vals[0]; vals[1] = mat.vals[1]; vals[2] = mat.vals[2]; vals[3] = mat.vals[3]; vals[4] = mat.vals[4]; vals[5] = mat.vals[5]; vals[6] = mat.vals[6]; vals[7] = mat.vals[7]; vals[8] = mat.vals[8]; return this; } /** Adds a translational component to the matrix in the 3rd column. The other columns are untouched. * @param vector The translation vector * @return This matrix for chaining */ public Matrix3 trn (Vector3 vector) { vals[6] += vector.x; vals[7] += vector.y; return this; } /** Adds a translational component to the matrix in the 3rd column. The other columns are untouched. * @param x The x-component of the translation vector * @param y The y-component of the translation vector * @return This matrix for chaining */ public Matrix3 trn (float x, float y) { vals[6] += x; vals[7] += y; return this; } /** Postmultiplies this matrix by a translation matrix. Postmultiplication is also used by OpenGL ES' * glTranslate/glRotate/glScale * @param x * @param y * @return this matrix for chaining */ public Matrix3 translate (float x, float y) { tmp[0] = 1; tmp[1] = 0; tmp[2] = 0; tmp[3] = 0; tmp[4] = 1; tmp[5] = 0; tmp[6] = x; tmp[7] = y; tmp[8] = 1; mul(vals, tmp); return this; } /** Postmultiplies this matrix with a (counter-clockwise) rotation matrix. Postmultiplication is also used by OpenGL ES' * glTranslate/glRotate/glScale * @param angle the angle in degrees * @return this matrix for chaining */ public Matrix3 rotate (float angle) { if (angle == 0) return this; angle = DEGREE_TO_RAD * angle; float cos = (float)Math.cos(angle); float sin = (float)Math.sin(angle); tmp[0] = cos; tmp[1] = sin; tmp[2] = 0; tmp[3] = -sin; tmp[4] = cos; tmp[5] = 0; tmp[6] = 0; tmp[7] = 0; tmp[8] = 1; mul(vals, tmp); return this; } /** Postmultiplies this matrix with a scale matrix. Postmultiplication is also used by OpenGL ES' glTranslate/glRotate/glScale. * @param scaleX * @param scaleY * @return this matrix for chaining */ public Matrix3 scale (float scaleX, float scaleY) { tmp[0] = scaleX; tmp[1] = 0; tmp[2] = 0; tmp[3] = 0; tmp[4] = scaleY; tmp[5] = 0; tmp[6] = 0; tmp[7] = 0; tmp[8] = 1; mul(vals, tmp); return this; } public float[] getValues () { return vals; } private static void mul (float[] mata, float[] matb) { float v00 = mata[0] * matb[0] + mata[3] * matb[1] + mata[6] * matb[2]; float v01 = mata[0] * matb[3] + mata[3] * matb[4] + mata[6] * matb[5]; float v02 = mata[0] * matb[6] + mata[3] * matb[7] + mata[6] * matb[8]; float v10 = mata[1] * matb[0] + mata[4] * matb[1] + mata[7] * matb[2]; float v11 = mata[1] * matb[3] + mata[4] * matb[4] + mata[7] * matb[5]; float v12 = mata[1] * matb[6] + mata[4] * matb[7] + mata[7] * matb[8]; float v20 = mata[2] * matb[0] + mata[5] * matb[1] + mata[8] * matb[2]; float v21 = mata[2] * matb[3] + mata[5] * matb[4] + mata[8] * matb[5]; float v22 = mata[2] * matb[6] + mata[5] * matb[7] + mata[8] * matb[8]; mata[0] = v00; mata[1] = v10; mata[2] = v20; mata[3] = v01; mata[4] = v11; mata[5] = v21; mata[6] = v02; mata[7] = v12; mata[8] = v22; } }
true
true
public Matrix3 inv () { float det = det(); if (det == 0) throw new GdxRuntimeException("Can't invert a singular matrix"); float inv_det = 1.0f / det; float tmp[] = {0, 0, 0, 0, 0, 0, 0, 0, 0}; tmp[0] = vals[4] * vals[8] - vals[5] * vals[7]; tmp[1] = vals[2] * vals[7] - vals[1] * vals[8]; tmp[2] = vals[1] * vals[5] - vals[2] * vals[4]; tmp[3] = vals[5] * vals[6] - vals[3] * vals[8]; tmp[4] = vals[0] * vals[8] - vals[2] * vals[6]; tmp[5] = vals[2] * vals[3] - vals[0] * vals[5]; tmp[6] = vals[3] * vals[7] - vals[4] * vals[6]; tmp[7] = vals[1] * vals[6] - vals[0] * vals[7]; tmp[8] = vals[0] * vals[4] - vals[1] * vals[3]; vals[0] = inv_det * tmp[0]; vals[1] = inv_det * tmp[1]; vals[2] = inv_det * tmp[2]; vals[3] = inv_det * tmp[3]; vals[4] = inv_det * tmp[4]; vals[5] = inv_det * tmp[5]; vals[6] = inv_det * tmp[6]; vals[7] = inv_det * tmp[7]; vals[8] = inv_det * tmp[8]; return this; }
public Matrix3 inv () { float det = det(); if (det == 0) throw new GdxRuntimeException("Can't invert a singular matrix"); float inv_det = 1.0f / det; tmp[0] = vals[4] * vals[8] - vals[5] * vals[7]; tmp[1] = vals[2] * vals[7] - vals[1] * vals[8]; tmp[2] = vals[1] * vals[5] - vals[2] * vals[4]; tmp[3] = vals[5] * vals[6] - vals[3] * vals[8]; tmp[4] = vals[0] * vals[8] - vals[2] * vals[6]; tmp[5] = vals[2] * vals[3] - vals[0] * vals[5]; tmp[6] = vals[3] * vals[7] - vals[4] * vals[6]; tmp[7] = vals[1] * vals[6] - vals[0] * vals[7]; tmp[8] = vals[0] * vals[4] - vals[1] * vals[3]; vals[0] = inv_det * tmp[0]; vals[1] = inv_det * tmp[1]; vals[2] = inv_det * tmp[2]; vals[3] = inv_det * tmp[3]; vals[4] = inv_det * tmp[4]; vals[5] = inv_det * tmp[5]; vals[6] = inv_det * tmp[6]; vals[7] = inv_det * tmp[7]; vals[8] = inv_det * tmp[8]; return this; }
diff --git a/src/main/java/org/dynjs/parser/Executor.java b/src/main/java/org/dynjs/parser/Executor.java index e281631f..a564a291 100644 --- a/src/main/java/org/dynjs/parser/Executor.java +++ b/src/main/java/org/dynjs/parser/Executor.java @@ -1,422 +1,421 @@ /** * Copyright 2011 dynjs contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dynjs.parser; import me.qmx.internal.org.objectweb.asm.Opcodes; import me.qmx.jitescript.CodeBlock; import org.antlr.runtime.tree.CommonTree; import org.dynjs.api.Function; import org.dynjs.api.Scope; import org.dynjs.compiler.DynJSCompiler; import org.dynjs.parser.statement.BlockStatement; import org.dynjs.runtime.DynAtom; import org.dynjs.runtime.DynNumber; import org.dynjs.runtime.DynThreadContext; import org.dynjs.runtime.RT; import org.dynjs.runtime.primitives.DynPrimitiveNumber; import org.dynjs.runtime.primitives.DynPrimitiveUndefined; import java.util.List; import static me.qmx.jitescript.util.CodegenUtils.ci; import static me.qmx.jitescript.util.CodegenUtils.p; import static me.qmx.jitescript.util.CodegenUtils.sig; public class Executor implements Opcodes { private DynJSCompiler compiler = new DynJSCompiler(); private final DynThreadContext context; public Executor(DynThreadContext context) { this.context = context; } public DynThreadContext getContext() { return context; } public List<Statement> program(final List<Statement> blockContent) { return blockContent; } public Statement block(final List<Statement> blockContent) { return new BlockStatement(blockContent); } public Statement printStatement(final Statement expr) { return new Statement() { @Override public CodeBlock getCodeBlock() { return newCodeBlock(expr) .aprintln(); } }; } public Statement declareVar(final CommonTree id) { return declareVar(id, new Statement() { @Override public CodeBlock getCodeBlock() { return newCodeBlock() .getstatic(p(DynPrimitiveUndefined.class), "UNDEFINED", ci(DynPrimitiveUndefined.class)); } }); } public Statement declareVar(final CommonTree id, final Statement expr) { return declareVar(id.getText(), expr); } public Statement declareVar(final String id, final Statement expr) { return new Statement() { @Override public CodeBlock getCodeBlock() { return newCodeBlock(expr) .astore(3) .aload(2) .ldc(id) .aload(3) .invokedynamic("dynjs:scope:define", sig(void.class, Scope.class, String.class, DynAtom.class), RT.BOOTSTRAP, RT.BOOTSTRAP_ARGS); } }; } public Statement defineAddOp(final Statement l, final Statement r) { return defineNumOp("add", l, r); } public Statement defineSubOp(final Statement l, final Statement r) { return defineNumOp("sub", l, r); } public Statement defineMulOp(final Statement l, final Statement r) { return defineNumOp("mul", l, r); } public Statement defineNumOp(final String op, final Statement l, final Statement r) { return new Statement() { @Override public CodeBlock getCodeBlock() { String instruction = "dynjs:bop:" + op; return newCodeBlock() .append(l.getCodeBlock()) .append(r.getCodeBlock()) .invokedynamic(instruction, sig(DynNumber.class, DynAtom.class, DynAtom.class), RT.BOOTSTRAP, RT.BOOTSTRAP_ARGS); } }; } public Statement defineStringLiteral(final String literal) { return new Statement() { @Override public CodeBlock getCodeBlock() { return newCodeBlock() .aload(1) .ldc(literal) .invokevirtual(p(DynThreadContext.class), "defineStringLiteral", sig(DynAtom.class, String.class)); } }; } public Statement defineOctalLiteral(final String value) { return new Statement() { @Override public CodeBlock getCodeBlock() { return newCodeBlock() .aload(1) .ldc(value) .invokevirtual(p(DynThreadContext.class), "defineOctalLiteral", sig(DynPrimitiveNumber.class, String.class)); } }; } public Statement resolveIdentifier(final CommonTree id) { return new Statement() { @Override public CodeBlock getCodeBlock() { return newCodeBlock() .aload(2) .ldc(id.getText()) .invokedynamic("dynjs:scope:resolve", sig(DynAtom.class, Scope.class, String.class), RT.BOOTSTRAP, RT.BOOTSTRAP_ARGS); } }; } public Statement defineNumberLiteral(final String value) { return new Statement() { @Override public CodeBlock getCodeBlock() { return newCodeBlock() .aload(1) .ldc(value) .invokevirtual(p(DynThreadContext.class), "defineDecimalLiteral", sig(DynPrimitiveNumber.class, String.class)); } }; } public Statement defineFunction(final String identifier, final List<String> args, final Statement block) { // put arguments on stack final Integer slot = getContext().store(block.getCodeBlock()); Statement statement = new Statement() { @Override public CodeBlock getCodeBlock() { CodeBlock codeBlock = newCodeBlock(); codeBlock = codeBlock .bipush(args.size()) .anewarray(p(String.class)) .astore(4); for (String arg : args) { codeBlock = codeBlock .ldc(arg) .aastore(); } codeBlock = codeBlock .aload(1) .bipush(slot) - .aload(3) .aload(4) - .invokedynamic("dynjs:compile:function", sig(Function.class, DynThreadContext.class, Integer.class, String[].class), RT.BOOTSTRAP, RT.BOOTSTRAP_ARGS); + .invokedynamic("dynjs:compile:function", sig(Function.class, DynThreadContext.class, int.class, String[].class), RT.BOOTSTRAP, RT.BOOTSTRAP_ARGS); return codeBlock; } }; return statement; } public Statement defineShlOp(Statement l, Statement r) { return null; } public Statement defineShrOp(Statement l, Statement r) { return null; } public Statement defineShuOp(Statement l, Statement r) { return null; } public Statement defineDivOp(Statement l, Statement r) { return null; } public Statement defineModOp(Statement l, Statement r) { return null; } public Statement defineDeleteOp(Statement expression) { return null; } public Statement defineVoidOp(Statement expression) { return null; } public Statement defineTypeOfOp(Statement expression) { return null; } public Statement defineIncOp(Statement expression) { return null; } public Statement defineDecOp(Statement expression) { return null; } public Statement definePosOp(Statement expression) { return null; } public Statement defineNegOp(Statement expression) { return null; } public Statement defineInvOp(Statement expression) { return null; } public Statement defineNotOp(Statement expression) { return null; } public Statement definePIncOp(Statement expression) { return null; } public Statement definePDecOp(Statement expression) { return null; } public Statement defineLtRelOp(Statement l, Statement r) { return null; } public Statement defineGtRelOp(Statement l, Statement r) { return null; } public Statement defineLteRelOp(Statement l, Statement r) { return null; } public Statement defineGteRelOp(Statement l, Statement r) { return null; } public Statement defineInstanceOfRelOp(Statement l, Statement r) { return null; } public Statement defineInRelOp(Statement l, Statement r) { return null; } public Statement defineLorOp(Statement l, Statement r) { return null; } public Statement defineLandOp(Statement l, Statement r) { return null; } public Statement defineAndBitOp(Statement l, Statement r) { return null; } public Statement defineOrBitOp(Statement l, Statement r) { return null; } public Statement defineXorBitOp(Statement l, Statement r) { return null; } public Statement defineEqOp(Statement l, Statement r) { return null; } public Statement defineNEqOp(Statement l, Statement r) { return null; } public Statement defineSameOp(Statement l, Statement r) { return null; } public Statement defineNSameOp(Statement l, Statement r) { return null; } public Statement defineAssOp(Statement l, Statement r) { return null; } public Statement defineMulAssOp(Statement l, Statement r) { return null; } public Statement defineDivAssOp(Statement l, Statement r) { return null; } public Statement defineModAssOp(Statement l, Statement r) { return null; } public Statement defineAddAssOp(Statement l, Statement r) { return null; } public Statement defineSubAssOp(Statement l, Statement r) { return null; } public Statement defineShlAssOp(Statement l, Statement r) { return null; } public Statement defineShrAssOp(Statement l, Statement r) { return null; } public Statement defineShuAssOp(Statement l, Statement r) { return null; } public Statement defineAndAssOp(Statement l, Statement r) { return null; } public Statement defineXorAssOp(Statement l, Statement r) { return null; } public Statement defineOrAssOp(Statement l, Statement r) { return null; } public Statement defineQueOp(Statement ex1, Statement ex2, Statement ex3) { return null; } public Statement defineThisLiteral() { return null; //To change body of created methods use File | Settings | File Templates. } public Statement defineNullLiteral() { return null; //To change body of created methods use File | Settings | File Templates. } public Statement defineRegExLiteral(String s) { return null; //To change body of created methods use File | Settings | File Templates. } public Statement defineTrueLiteral() { return null; //To change body of created methods use File | Settings | File Templates. } public Statement defineFalseLiteral() { return null; //To change body of created methods use File | Settings | File Templates. } public Statement defineHexaLiteral(String s) { return null; //To change body of created methods use File | Settings | File Templates. } public Statement executeNew(Statement leftHandSideExpression10) { return null; //To change body of created methods use File | Settings | File Templates. } public Statement resolveByField(String s, Statement leftHandSideExpression13) { return null; //To change body of created methods use File | Settings | File Templates. } public Statement defineByIndex(Statement leftHandSideExpression11) { return null; //To change body of created methods use File | Settings | File Templates. } public CodeBlock newCodeBlock(Statement stmt) { if (stmt != null) { return stmt.getCodeBlock(); } else { return newCodeBlock(); } } private CodeBlock newCodeBlock() { return CodeBlock.newCodeBlock(); } }
false
true
public Statement defineFunction(final String identifier, final List<String> args, final Statement block) { // put arguments on stack final Integer slot = getContext().store(block.getCodeBlock()); Statement statement = new Statement() { @Override public CodeBlock getCodeBlock() { CodeBlock codeBlock = newCodeBlock(); codeBlock = codeBlock .bipush(args.size()) .anewarray(p(String.class)) .astore(4); for (String arg : args) { codeBlock = codeBlock .ldc(arg) .aastore(); } codeBlock = codeBlock .aload(1) .bipush(slot) .aload(3) .aload(4) .invokedynamic("dynjs:compile:function", sig(Function.class, DynThreadContext.class, Integer.class, String[].class), RT.BOOTSTRAP, RT.BOOTSTRAP_ARGS); return codeBlock; } }; return statement; }
public Statement defineFunction(final String identifier, final List<String> args, final Statement block) { // put arguments on stack final Integer slot = getContext().store(block.getCodeBlock()); Statement statement = new Statement() { @Override public CodeBlock getCodeBlock() { CodeBlock codeBlock = newCodeBlock(); codeBlock = codeBlock .bipush(args.size()) .anewarray(p(String.class)) .astore(4); for (String arg : args) { codeBlock = codeBlock .ldc(arg) .aastore(); } codeBlock = codeBlock .aload(1) .bipush(slot) .aload(4) .invokedynamic("dynjs:compile:function", sig(Function.class, DynThreadContext.class, int.class, String[].class), RT.BOOTSTRAP, RT.BOOTSTRAP_ARGS); return codeBlock; } }; return statement; }
diff --git a/integration-test/src/test/java/net/nelz/simplesm/test/UpdateAssignCacheTest.java b/integration-test/src/test/java/net/nelz/simplesm/test/UpdateAssignCacheTest.java index 744fdaa..e366a1e 100644 --- a/integration-test/src/test/java/net/nelz/simplesm/test/UpdateAssignCacheTest.java +++ b/integration-test/src/test/java/net/nelz/simplesm/test/UpdateAssignCacheTest.java @@ -1,65 +1,65 @@ package net.nelz.simplesm.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.testng.AssertJUnit.*; import net.nelz.simplesm.test.svc.TestSvc; import java.util.List; import java.util.ArrayList; /** Copyright (c) 2008 Nelson Carpentier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ public class UpdateAssignCacheTest { private ApplicationContext context; @BeforeClass public void beforeClass() { context = new ClassPathXmlApplicationContext("/test-context.xml"); } @Test public void test() { final TestSvc test = (TestSvc) context.getBean("testSvc"); final List<String> result1 = test.getAssignStrings(); final List<String> altData = new ArrayList<String>(); for (int ix = 0; ix < result1.size(); ix++) { if (ix % 2 == 0) { altData.add(result1.get(ix)); } } test.updateAssignStrings(altData); final List<String> result2 = test.getAssignStrings(); assertNotSame(result1.size(), result2.size()); assertEquals(altData.size(), result2.size()); - for (int ix = 0; ix < result1.size(); ix++) { + for (int ix = 0; ix < result2.size(); ix++) { assertEquals(altData.get(ix), result2.get(ix)); } } }
true
true
public void test() { final TestSvc test = (TestSvc) context.getBean("testSvc"); final List<String> result1 = test.getAssignStrings(); final List<String> altData = new ArrayList<String>(); for (int ix = 0; ix < result1.size(); ix++) { if (ix % 2 == 0) { altData.add(result1.get(ix)); } } test.updateAssignStrings(altData); final List<String> result2 = test.getAssignStrings(); assertNotSame(result1.size(), result2.size()); assertEquals(altData.size(), result2.size()); for (int ix = 0; ix < result1.size(); ix++) { assertEquals(altData.get(ix), result2.get(ix)); } }
public void test() { final TestSvc test = (TestSvc) context.getBean("testSvc"); final List<String> result1 = test.getAssignStrings(); final List<String> altData = new ArrayList<String>(); for (int ix = 0; ix < result1.size(); ix++) { if (ix % 2 == 0) { altData.add(result1.get(ix)); } } test.updateAssignStrings(altData); final List<String> result2 = test.getAssignStrings(); assertNotSame(result1.size(), result2.size()); assertEquals(altData.size(), result2.size()); for (int ix = 0; ix < result2.size(); ix++) { assertEquals(altData.get(ix), result2.get(ix)); } }
diff --git a/src/com/android/phone/PhoneApp.java b/src/com/android/phone/PhoneApp.java index f4b3cae4..38cd7f68 100644 --- a/src/com/android/phone/PhoneApp.java +++ b/src/com/android/phone/PhoneApp.java @@ -1,2021 +1,2022 @@ /* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.phone; import android.app.Activity; import android.app.Application; import android.app.KeyguardManager; import android.app.PendingIntent; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothHeadset; import android.bluetooth.BluetoothProfile; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Configuration; import android.media.AudioManager; import android.net.Uri; import android.os.AsyncResult; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.os.IPowerManager; import android.os.LocalPowerManager; import android.os.Message; import android.os.PowerManager; import android.os.RemoteException; import android.os.ServiceManager; import android.os.SystemClock; import android.os.SystemProperties; import android.os.UpdateLock; import android.preference.PreferenceManager; import android.provider.Settings.System; import android.telephony.ServiceState; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import com.android.internal.telephony.Call; import com.android.internal.telephony.CallManager; import com.android.internal.telephony.IccCard; import com.android.internal.telephony.MmiCode; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneFactory; import com.android.internal.telephony.TelephonyCapabilities; import com.android.internal.telephony.TelephonyIntents; import com.android.internal.telephony.cdma.TtyIntent; import com.android.phone.OtaUtils.CdmaOtaScreenState; import com.android.server.sip.SipService; /** * Top-level Application class for the Phone app. */ public class PhoneApp extends Application implements AccelerometerListener.OrientationListener { /* package */ static final String LOG_TAG = "PhoneApp"; /** * Phone app-wide debug level: * 0 - no debug logging * 1 - normal debug logging if ro.debuggable is set (which is true in * "eng" and "userdebug" builds but not "user" builds) * 2 - ultra-verbose debug logging * * Most individual classes in the phone app have a local DBG constant, * typically set to * (PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1) * or else * (PhoneApp.DBG_LEVEL >= 2) * depending on the desired verbosity. * * ***** DO NOT SUBMIT WITH DBG_LEVEL > 0 ************* */ /* package */ static final int DBG_LEVEL = 0; private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1); private static final boolean VDBG = (PhoneApp.DBG_LEVEL >= 2); // Message codes; see mHandler below. private static final int EVENT_SIM_NETWORK_LOCKED = 3; private static final int EVENT_WIRED_HEADSET_PLUG = 7; private static final int EVENT_SIM_STATE_CHANGED = 8; private static final int EVENT_UPDATE_INCALL_NOTIFICATION = 9; private static final int EVENT_DATA_ROAMING_DISCONNECTED = 10; private static final int EVENT_DATA_ROAMING_OK = 11; private static final int EVENT_UNSOL_CDMA_INFO_RECORD = 12; private static final int EVENT_DOCK_STATE_CHANGED = 13; private static final int EVENT_TTY_PREFERRED_MODE_CHANGED = 14; private static final int EVENT_TTY_MODE_GET = 15; private static final int EVENT_TTY_MODE_SET = 16; private static final int EVENT_START_SIP_SERVICE = 17; // The MMI codes are also used by the InCallScreen. public static final int MMI_INITIATE = 51; public static final int MMI_COMPLETE = 52; public static final int MMI_CANCEL = 53; // Don't use message codes larger than 99 here; those are reserved for // the individual Activities of the Phone UI. /** * Allowable values for the poke lock code (timeout between a user activity and the * going to sleep), please refer to {@link com.android.server.PowerManagerService} * for additional reference. * SHORT uses the short delay for the timeout (SHORT_KEYLIGHT_DELAY, 6 sec) * MEDIUM uses the medium delay for the timeout (MEDIUM_KEYLIGHT_DELAY, 15 sec) * DEFAULT is the system-wide default delay for the timeout (1 min) */ public enum ScreenTimeoutDuration { SHORT, MEDIUM, DEFAULT } /** * Allowable values for the wake lock code. * SLEEP means the device can be put to sleep. * PARTIAL means wake the processor, but we display can be kept off. * FULL means wake both the processor and the display. */ public enum WakeState { SLEEP, PARTIAL, FULL } /** * Intent Action used for hanging up the current call from Notification bar. This will * choose first ringing call, first active call, or first background call (typically in * HOLDING state). */ public static final String ACTION_HANG_UP_ONGOING_CALL = "com.android.phone.ACTION_HANG_UP_ONGOING_CALL"; /** * Intent Action used for making a phone call from Notification bar. * This is for missed call notifications. */ public static final String ACTION_CALL_BACK_FROM_NOTIFICATION = "com.android.phone.ACTION_CALL_BACK_FROM_NOTIFICATION"; /** * Intent Action used for sending a SMS from notification bar. * This is for missed call notifications. */ public static final String ACTION_SEND_SMS_FROM_NOTIFICATION = "com.android.phone.ACTION_SEND_SMS_FROM_NOTIFICATION"; private static PhoneApp sMe; // A few important fields we expose to the rest of the package // directly (rather than thru set/get methods) for efficiency. Phone phone; CallController callController; InCallUiState inCallUiState; CallerInfoCache callerInfoCache; CallNotifier notifier; NotificationMgr notificationMgr; Ringer ringer; BluetoothHandsfree mBtHandsfree; PhoneInterfaceManager phoneMgr; CallManager mCM; int mBluetoothHeadsetState = BluetoothProfile.STATE_DISCONNECTED; int mBluetoothHeadsetAudioState = BluetoothHeadset.STATE_AUDIO_DISCONNECTED; boolean mShowBluetoothIndication = false; static int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED; static boolean sVoiceCapable = true; // Internal PhoneApp Call state tracker CdmaPhoneCallState cdmaPhoneCallState; // The InCallScreen instance (or null if the InCallScreen hasn't been // created yet.) private InCallScreen mInCallScreen; // The currently-active PUK entry activity and progress dialog. // Normally, these are the Emergency Dialer and the subsequent // progress dialog. null if there is are no such objects in // the foreground. private Activity mPUKEntryActivity; private ProgressDialog mPUKEntryProgressDialog; private boolean mIsSimPinEnabled; private String mCachedSimPin; // True if a wired headset is currently plugged in, based on the state // from the latest Intent.ACTION_HEADSET_PLUG broadcast we received in // mReceiver.onReceive(). private boolean mIsHeadsetPlugged; // True if the keyboard is currently *not* hidden // Gets updated whenever there is a Configuration change private boolean mIsHardKeyboardOpen; // True if we are beginning a call, but the phone state has not changed yet private boolean mBeginningCall; // Last phone state seen by updatePhoneState() private Phone.State mLastPhoneState = Phone.State.IDLE; private WakeState mWakeState = WakeState.SLEEP; /** * Timeout setting used by PokeLock. * * This variable won't be effective when proximity sensor is available in the device. * * @see ScreenTimeoutDuration */ private ScreenTimeoutDuration mScreenTimeoutDuration = ScreenTimeoutDuration.DEFAULT; /** * Used to set/unset {@link LocalPowerManager#POKE_LOCK_IGNORE_TOUCH_EVENTS} toward PokeLock. * * This variable won't be effective when proximity sensor is available in the device. */ private boolean mIgnoreTouchUserActivity = false; private final IBinder mPokeLockToken = new Binder(); private IPowerManager mPowerManagerService; private PowerManager.WakeLock mWakeLock; private PowerManager.WakeLock mPartialWakeLock; private PowerManager.WakeLock mProximityWakeLock; private KeyguardManager mKeyguardManager; private AccelerometerListener mAccelerometerListener; private int mOrientation = AccelerometerListener.ORIENTATION_UNKNOWN; private UpdateLock mUpdateLock; // Broadcast receiver for various intent broadcasts (see onCreate()) private final BroadcastReceiver mReceiver = new PhoneAppBroadcastReceiver(); // Broadcast receiver purely for ACTION_MEDIA_BUTTON broadcasts private final BroadcastReceiver mMediaButtonReceiver = new MediaButtonBroadcastReceiver(); /** boolean indicating restoring mute state on InCallScreen.onResume() */ private boolean mShouldRestoreMuteOnInCallResume; /** * The singleton OtaUtils instance used for OTASP calls. * * The OtaUtils instance is created lazily the first time we need to * make an OTASP call, regardless of whether it's an interactive or * non-interactive OTASP call. */ public OtaUtils otaUtils; // Following are the CDMA OTA information Objects used during OTA Call. // cdmaOtaProvisionData object store static OTA information that needs // to be maintained even during Slider open/close scenarios. // cdmaOtaConfigData object stores configuration info to control visiblity // of each OTA Screens. // cdmaOtaScreenState object store OTA Screen State information. public OtaUtils.CdmaOtaProvisionData cdmaOtaProvisionData; public OtaUtils.CdmaOtaConfigData cdmaOtaConfigData; public OtaUtils.CdmaOtaScreenState cdmaOtaScreenState; public OtaUtils.CdmaOtaInCallScreenUiState cdmaOtaInCallScreenUiState; // TTY feature enabled on this platform private boolean mTtyEnabled; // Current TTY operating mode selected by user private int mPreferredTtyMode = Phone.TTY_MODE_OFF; /** * Set the restore mute state flag. Used when we are setting the mute state * OUTSIDE of user interaction {@link PhoneUtils#startNewCall(Phone)} */ /*package*/void setRestoreMuteOnInCallResume (boolean mode) { mShouldRestoreMuteOnInCallResume = mode; } /** * Get the restore mute state flag. * This is used by the InCallScreen {@link InCallScreen#onResume()} to figure * out if we need to restore the mute state for the current active call. */ /*package*/boolean getRestoreMuteOnInCallResume () { return mShouldRestoreMuteOnInCallResume; } Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { Phone.State phoneState; switch (msg.what) { // Starts the SIP service. It's a no-op if SIP API is not supported // on the deivce. // TODO: Having the phone process host the SIP service is only // temporary. Will move it to a persistent communication process // later. case EVENT_START_SIP_SERVICE: SipService.start(getApplicationContext()); break; // TODO: This event should be handled by the lock screen, just // like the "SIM missing" and "Sim locked" cases (bug 1804111). case EVENT_SIM_NETWORK_LOCKED: if (getResources().getBoolean(R.bool.ignore_sim_network_locked_events)) { // Some products don't have the concept of a "SIM network lock" Log.i(LOG_TAG, "Ignoring EVENT_SIM_NETWORK_LOCKED event; " + "not showing 'SIM network unlock' PIN entry screen"); } else { // Normal case: show the "SIM network unlock" PIN entry screen. // The user won't be able to do anything else until // they enter a valid SIM network PIN. Log.i(LOG_TAG, "show sim depersonal panel"); IccNetworkDepersonalizationPanel ndpPanel = new IccNetworkDepersonalizationPanel(PhoneApp.getInstance()); ndpPanel.show(); } break; case EVENT_UPDATE_INCALL_NOTIFICATION: // Tell the NotificationMgr to update the "ongoing // call" icon in the status bar, if necessary. // Currently, this is triggered by a bluetooth headset // state change (since the status bar icon needs to // turn blue when bluetooth is active.) if (DBG) Log.d (LOG_TAG, "- updating in-call notification from handler..."); notificationMgr.updateInCallNotification(); break; case EVENT_DATA_ROAMING_DISCONNECTED: notificationMgr.showDataDisconnectedRoaming(); break; case EVENT_DATA_ROAMING_OK: notificationMgr.hideDataDisconnectedRoaming(); break; case MMI_COMPLETE: onMMIComplete((AsyncResult) msg.obj); break; case MMI_CANCEL: PhoneUtils.cancelMmiCode(phone); break; case EVENT_WIRED_HEADSET_PLUG: // Since the presence of a wired headset or bluetooth affects the // speakerphone, update the "speaker" state. We ONLY want to do // this on the wired headset connect / disconnect events for now // though, so we're only triggering on EVENT_WIRED_HEADSET_PLUG. phoneState = mCM.getState(); // Do not change speaker state if phone is not off hook if (phoneState == Phone.State.OFFHOOK) { if (mBtHandsfree == null || !mBtHandsfree.isAudioOn()) { if (!isHeadsetPlugged()) { // if the state is "not connected", restore the speaker state. PhoneUtils.restoreSpeakerMode(getApplicationContext()); } else { // if the state is "connected", force the speaker off without // storing the state. PhoneUtils.turnOnSpeaker(getApplicationContext(), false, false); } } } // Update the Proximity sensor based on headset state updateProximitySensorMode(phoneState); // Force TTY state update according to new headset state if (mTtyEnabled) { sendMessage(obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0)); } break; case EVENT_SIM_STATE_CHANGED: // Marks the event where the SIM goes into ready state. // Right now, this is only used for the PUK-unlocking // process. if (msg.obj.equals(IccCard.INTENT_VALUE_ICC_READY)) { // when the right event is triggered and there // are UI objects in the foreground, we close // them to display the lock panel. if (mPUKEntryActivity != null) { mPUKEntryActivity.finish(); mPUKEntryActivity = null; } if (mPUKEntryProgressDialog != null) { mPUKEntryProgressDialog.dismiss(); mPUKEntryProgressDialog = null; } } break; case EVENT_UNSOL_CDMA_INFO_RECORD: //TODO: handle message here; break; case EVENT_DOCK_STATE_CHANGED: // If the phone is docked/undocked during a call, and no wired or BT headset // is connected: turn on/off the speaker accordingly. boolean inDockMode = false; if (mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED) { inDockMode = true; } if (VDBG) Log.d(LOG_TAG, "received EVENT_DOCK_STATE_CHANGED. Phone inDock = " + inDockMode); phoneState = mCM.getState(); if (phoneState == Phone.State.OFFHOOK && !isHeadsetPlugged() && !(mBtHandsfree != null && mBtHandsfree.isAudioOn())) { PhoneUtils.turnOnSpeaker(getApplicationContext(), inDockMode, true); updateInCallScreen(); // Has no effect if the InCallScreen isn't visible } break; case EVENT_TTY_PREFERRED_MODE_CHANGED: // TTY mode is only applied if a headset is connected int ttyMode; if (isHeadsetPlugged()) { ttyMode = mPreferredTtyMode; } else { ttyMode = Phone.TTY_MODE_OFF; } phone.setTTYMode(ttyMode, mHandler.obtainMessage(EVENT_TTY_MODE_SET)); break; case EVENT_TTY_MODE_GET: handleQueryTTYModeResponse(msg); break; case EVENT_TTY_MODE_SET: handleSetTTYModeResponse(msg); break; } } }; public PhoneApp() { sMe = this; } @Override public void onCreate() { if (VDBG) Log.v(LOG_TAG, "onCreate()..."); ContentResolver resolver = getContentResolver(); // Cache the "voice capable" flag. // This flag currently comes from a resource (which is // overrideable on a per-product basis): sVoiceCapable = getResources().getBoolean(com.android.internal.R.bool.config_voice_capable); // ...but this might eventually become a PackageManager "system // feature" instead, in which case we'd do something like: // sVoiceCapable = // getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY_VOICE_CALLS); if (phone == null) { // Initialize the telephony framework PhoneFactory.makeDefaultPhones(this); // Get the default phone phone = PhoneFactory.getDefaultPhone(); // Start TelephonyDebugService After the default phone is created. Intent intent = new Intent(this, TelephonyDebugService.class); startService(intent); mCM = CallManager.getInstance(); mCM.registerPhone(phone); // Create the NotificationMgr singleton, which is used to display // status bar icons and control other status bar behavior. notificationMgr = NotificationMgr.init(this); phoneMgr = PhoneInterfaceManager.init(this, phone); mHandler.sendEmptyMessage(EVENT_START_SIP_SERVICE); int phoneType = phone.getPhoneType(); if (phoneType == Phone.PHONE_TYPE_CDMA) { // Create an instance of CdmaPhoneCallState and initialize it to IDLE cdmaPhoneCallState = new CdmaPhoneCallState(); cdmaPhoneCallState.CdmaPhoneCallStateInit(); } if (BluetoothAdapter.getDefaultAdapter() != null) { // Start BluetoothHandsree even if device is not voice capable. // The device can still support VOIP. mBtHandsfree = BluetoothHandsfree.init(this, mCM); startService(new Intent(this, BluetoothHeadsetService.class)); } else { // Device is not bluetooth capable mBtHandsfree = null; } ringer = Ringer.init(this); // before registering for phone state changes PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK - | PowerManager.ACQUIRE_CAUSES_WAKEUP, + | PowerManager.ACQUIRE_CAUSES_WAKEUP + | PowerManager.ON_AFTER_RELEASE, LOG_TAG); // lock used to keep the processor awake, when we don't care for the display. mPartialWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, LOG_TAG); // Wake lock used to control proximity sensor behavior. if ((pm.getSupportedWakeLockFlags() & PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) != 0x0) { mProximityWakeLock = pm.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, LOG_TAG); } if (DBG) Log.d(LOG_TAG, "onCreate: mProximityWakeLock: " + mProximityWakeLock); // create mAccelerometerListener only if we are using the proximity sensor if (proximitySensorModeEnabled()) { mAccelerometerListener = new AccelerometerListener(this, this); } mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); // get a handle to the service so that we can use it later when we // want to set the poke lock. mPowerManagerService = IPowerManager.Stub.asInterface( ServiceManager.getService("power")); // Get UpdateLock to suppress system-update related events (e.g. dialog show-up) // during phone calls. mUpdateLock = new UpdateLock("phone"); if (DBG) Log.d(LOG_TAG, "onCreate: mUpdateLock: " + mUpdateLock); // Create the CallController singleton, which is the interface // to the telephony layer for user-initiated telephony functionality // (like making outgoing calls.) callController = CallController.init(this); // ...and also the InCallUiState instance, used by the CallController to // keep track of some "persistent state" of the in-call UI. inCallUiState = InCallUiState.init(this); // Create the CallerInfoCache singleton, which remembers custom ring tone and // send-to-voicemail settings. // // The asynchronous caching will start just after this call. callerInfoCache = CallerInfoCache.init(this); // Create the CallNotifer singleton, which handles // asynchronous events from the telephony layer (like // launching the incoming-call UI when an incoming call comes // in.) notifier = CallNotifier.init(this, phone, ringer, mBtHandsfree, new CallLogAsync()); // register for ICC status IccCard sim = phone.getIccCard(); if (sim != null) { if (VDBG) Log.v(LOG_TAG, "register for ICC status"); sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null); } // register for MMI/USSD mCM.registerForMmiComplete(mHandler, MMI_COMPLETE, null); // register connection tracking to PhoneUtils PhoneUtils.initializeConnectionHandler(mCM); // Read platform settings for TTY feature mTtyEnabled = getResources().getBoolean(R.bool.tty_enabled); // Register for misc other intent broadcasts. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED); intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED); intentFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED); intentFilter.addAction(Intent.ACTION_HEADSET_PLUG); intentFilter.addAction(Intent.ACTION_DOCK_EVENT); intentFilter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED); intentFilter.addAction(Intent.ACTION_SCREEN_OFF); intentFilter.addAction(Intent.ACTION_SCREEN_ON); if (mTtyEnabled) { intentFilter.addAction(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION); } intentFilter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); registerReceiver(mReceiver, intentFilter); // Use a separate receiver for ACTION_MEDIA_BUTTON broadcasts, // since we need to manually adjust its priority (to make sure // we get these intents *before* the media player.) IntentFilter mediaButtonIntentFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON); // TODO verify the independent priority doesn't need to be handled thanks to the // private intent handler registration // Make sure we're higher priority than the media player's // MediaButtonIntentReceiver (which currently has the default // priority of zero; see apps/Music/AndroidManifest.xml.) mediaButtonIntentFilter.setPriority(1); // registerReceiver(mMediaButtonReceiver, mediaButtonIntentFilter); // register the component so it gets priority for calls AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); am.registerMediaButtonEventReceiverForCalls(new ComponentName(this.getPackageName(), MediaButtonBroadcastReceiver.class.getName())); //set the default values for the preferences in the phone. PreferenceManager.setDefaultValues(this, R.xml.network_setting, false); PreferenceManager.setDefaultValues(this, R.xml.call_feature_setting, false); // Make sure the audio mode (along with some // audio-mode-related state of our own) is initialized // correctly, given the current state of the phone. PhoneUtils.setAudioMode(mCM); } if (TelephonyCapabilities.supportsOtasp(phone)) { cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData(); cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData(); cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState(); cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState(); } // XXX pre-load the SimProvider so that it's ready resolver.getType(Uri.parse("content://icc/adn")); // start with the default value to set the mute state. mShouldRestoreMuteOnInCallResume = false; // TODO: Register for Cdma Information Records // phone.registerCdmaInformationRecord(mHandler, EVENT_UNSOL_CDMA_INFO_RECORD, null); // Read TTY settings and store it into BP NV. // AP owns (i.e. stores) the TTY setting in AP settings database and pushes the setting // to BP at power up (BP does not need to make the TTY setting persistent storage). // This way, there is a single owner (i.e AP) for the TTY setting in the phone. if (mTtyEnabled) { mPreferredTtyMode = android.provider.Settings.Secure.getInt( phone.getContext().getContentResolver(), android.provider.Settings.Secure.PREFERRED_TTY_MODE, Phone.TTY_MODE_OFF); mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0)); } // Read HAC settings and configure audio hardware if (getResources().getBoolean(R.bool.hac_enabled)) { int hac = android.provider.Settings.System.getInt(phone.getContext().getContentResolver(), android.provider.Settings.System.HEARING_AID, 0); AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); audioManager.setParameter(CallFeaturesSetting.HAC_KEY, hac != 0 ? CallFeaturesSetting.HAC_VAL_ON : CallFeaturesSetting.HAC_VAL_OFF); } } @Override public void onConfigurationChanged(Configuration newConfig) { if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) { mIsHardKeyboardOpen = true; } else { mIsHardKeyboardOpen = false; } // Update the Proximity sensor based on keyboard state updateProximitySensorMode(mCM.getState()); super.onConfigurationChanged(newConfig); } /** * Returns the singleton instance of the PhoneApp. */ static PhoneApp getInstance() { return sMe; } /** * Returns the Phone associated with this instance */ static Phone getPhone() { return getInstance().phone; } Ringer getRinger() { return ringer; } BluetoothHandsfree getBluetoothHandsfree() { return mBtHandsfree; } /** * Returns an Intent that can be used to go to the "Call log" * UI (aka CallLogActivity) in the Contacts app. * * Watch out: there's no guarantee that the system has any activity to * handle this intent. (In particular there may be no "Call log" at * all on on non-voice-capable devices.) */ /* package */ static Intent createCallLogIntent() { Intent intent = new Intent(Intent.ACTION_VIEW, null); intent.setType("vnd.android.cursor.dir/calls"); return intent; } /** * Return an Intent that can be used to bring up the in-call screen. * * This intent can only be used from within the Phone app, since the * InCallScreen is not exported from our AndroidManifest. */ /* package */ static Intent createInCallIntent() { Intent intent = new Intent(Intent.ACTION_MAIN, null); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NO_USER_ACTION); intent.setClassName("com.android.phone", getCallScreenClassName()); return intent; } /** * Variation of createInCallIntent() that also specifies whether the * DTMF dialpad should be initially visible when the InCallScreen * comes up. */ /* package */ static Intent createInCallIntent(boolean showDialpad) { Intent intent = createInCallIntent(); intent.putExtra(InCallScreen.SHOW_DIALPAD_EXTRA, showDialpad); return intent; } /** * Returns PendingIntent for hanging up ongoing phone call. This will typically be used from * Notification context. */ /* package */ static PendingIntent createHangUpOngoingCallPendingIntent(Context context) { Intent intent = new Intent(PhoneApp.ACTION_HANG_UP_ONGOING_CALL, null, context, NotificationBroadcastReceiver.class); return PendingIntent.getBroadcast(context, 0, intent, 0); } /* package */ static PendingIntent getCallBackPendingIntent(Context context, String number) { Intent intent = new Intent(ACTION_CALL_BACK_FROM_NOTIFICATION, Uri.fromParts(Constants.SCHEME_TEL, number, null), context, NotificationBroadcastReceiver.class); return PendingIntent.getBroadcast(context, 0, intent, 0); } /* package */ static PendingIntent getSendSmsFromNotificationPendingIntent( Context context, String number) { Intent intent = new Intent(ACTION_SEND_SMS_FROM_NOTIFICATION, Uri.fromParts(Constants.SCHEME_SMSTO, number, null), context, NotificationBroadcastReceiver.class); return PendingIntent.getBroadcast(context, 0, intent, 0); } private static String getCallScreenClassName() { return InCallScreen.class.getName(); } /** * Starts the InCallScreen Activity. */ /* package */ void displayCallScreen() { if (VDBG) Log.d(LOG_TAG, "displayCallScreen()..."); // On non-voice-capable devices we shouldn't ever be trying to // bring up the InCallScreen in the first place. if (!sVoiceCapable) { Log.w(LOG_TAG, "displayCallScreen() not allowed: non-voice-capable device", new Throwable("stack dump")); // Include a stack trace since this warning // indicates a bug in our caller return; } try { startActivity(createInCallIntent()); } catch (ActivityNotFoundException e) { // It's possible that the in-call UI might not exist (like on // non-voice-capable devices), so don't crash if someone // accidentally tries to bring it up... Log.w(LOG_TAG, "displayCallScreen: transition to InCallScreen failed: " + e); } Profiler.callScreenRequested(); } boolean isSimPinEnabled() { return mIsSimPinEnabled; } boolean authenticateAgainstCachedSimPin(String pin) { return (mCachedSimPin != null && mCachedSimPin.equals(pin)); } void setCachedSimPin(String pin) { mCachedSimPin = pin; } void setInCallScreenInstance(InCallScreen inCallScreen) { mInCallScreen = inCallScreen; } /** * @return true if the in-call UI is running as the foreground * activity. (In other words, from the perspective of the * InCallScreen activity, return true between onResume() and * onPause().) * * Note this method will return false if the screen is currently off, * even if the InCallScreen *was* in the foreground just before the * screen turned off. (This is because the foreground activity is * always "paused" while the screen is off.) */ boolean isShowingCallScreen() { if (mInCallScreen == null) return false; return mInCallScreen.isForegroundActivity(); } /** * @return true if the in-call UI is running as the foreground activity, or, * it went to background due to screen being turned off. This might be useful * to determine if the in-call screen went to background because of other * activities, or its proximity sensor state or manual power-button press. * * Here are some examples. * * - If you want to know if the activity is in foreground or screen is turned off * from the in-call UI (i.e. though it is not "foreground" anymore it will become * so after screen being turned on), check * {@link #isShowingCallScreenForProximity()} is true or not. * {@link #updateProximitySensorMode(com.android.internal.telephony.Phone.State)} is * doing this. * * - If you want to know if the activity is not in foreground just because screen * is turned off (not due to other activity's interference), check * {@link #isShowingCallScreen()} is false *and* {@link #isShowingCallScreenForProximity()} * is true. InCallScreen#onDisconnect() is doing this check. * * @see #isShowingCallScreen() * * TODO: come up with better naming.. */ boolean isShowingCallScreenForProximity() { if (mInCallScreen == null) return false; return mInCallScreen.isForegroundActivityForProximity(); } /** * Dismisses the in-call UI. * * This also ensures that you won't be able to get back to the in-call * UI via the BACK button (since this call removes the InCallScreen * from the activity history.) * For OTA Call, it call InCallScreen api to handle OTA Call End scenario * to display OTA Call End screen. */ /* package */ void dismissCallScreen() { if (mInCallScreen != null) { if ((TelephonyCapabilities.supportsOtasp(phone)) && (mInCallScreen.isOtaCallInActiveState() || mInCallScreen.isOtaCallInEndState() || ((cdmaOtaScreenState != null) && (cdmaOtaScreenState.otaScreenState != CdmaOtaScreenState.OtaScreenState.OTA_STATUS_UNDEFINED)))) { // TODO: During OTA Call, display should not become dark to // allow user to see OTA UI update. Phone app needs to hold // a SCREEN_DIM_WAKE_LOCK wake lock during the entire OTA call. wakeUpScreen(); // If InCallScreen is not in foreground we resume it to show the OTA call end screen // Fire off the InCallScreen intent displayCallScreen(); mInCallScreen.handleOtaCallEnd(); return; } else { mInCallScreen.finish(); } } } /** * Handles OTASP-related events from the telephony layer. * * While an OTASP call is active, the CallNotifier forwards * OTASP-related telephony events to this method. */ void handleOtaspEvent(Message msg) { if (DBG) Log.d(LOG_TAG, "handleOtaspEvent(message " + msg + ")..."); if (otaUtils == null) { // We shouldn't be getting OTASP events without ever // having started the OTASP call in the first place! Log.w(LOG_TAG, "handleOtaEvents: got an event but otaUtils is null! " + "message = " + msg); return; } otaUtils.onOtaProvisionStatusChanged((AsyncResult) msg.obj); } /** * Similarly, handle the disconnect event of an OTASP call * by forwarding it to the OtaUtils instance. */ /* package */ void handleOtaspDisconnect() { if (DBG) Log.d(LOG_TAG, "handleOtaspDisconnect()..."); if (otaUtils == null) { // We shouldn't be getting OTASP events without ever // having started the OTASP call in the first place! Log.w(LOG_TAG, "handleOtaspDisconnect: otaUtils is null!"); return; } otaUtils.onOtaspDisconnect(); } /** * Sets the activity responsible for un-PUK-blocking the device * so that we may close it when we receive a positive result. * mPUKEntryActivity is also used to indicate to the device that * we are trying to un-PUK-lock the phone. In other words, iff * it is NOT null, then we are trying to unlock and waiting for * the SIM to move to READY state. * * @param activity is the activity to close when PUK has * finished unlocking. Can be set to null to indicate the unlock * or SIM READYing process is over. */ void setPukEntryActivity(Activity activity) { mPUKEntryActivity = activity; } Activity getPUKEntryActivity() { return mPUKEntryActivity; } /** * Sets the dialog responsible for notifying the user of un-PUK- * blocking - SIM READYing progress, so that we may dismiss it * when we receive a positive result. * * @param dialog indicates the progress dialog informing the user * of the state of the device. Dismissed upon completion of * READYing process */ void setPukEntryProgressDialog(ProgressDialog dialog) { mPUKEntryProgressDialog = dialog; } ProgressDialog getPUKEntryProgressDialog() { return mPUKEntryProgressDialog; } /** * Controls how quickly the screen times out. * * This is no-op when the device supports proximity sensor. * * The poke lock controls how long it takes before the screen powers * down, and therefore has no immediate effect when the current * WakeState (see {@link PhoneApp#requestWakeState}) is FULL. * If we're in a state where the screen *is* allowed to turn off, * though, the poke lock will determine the timeout interval (long or * short). */ /* package */ void setScreenTimeout(ScreenTimeoutDuration duration) { if (VDBG) Log.d(LOG_TAG, "setScreenTimeout(" + duration + ")..."); // stick with default timeout if we are using the proximity sensor if (proximitySensorModeEnabled()) { return; } // make sure we don't set the poke lock repeatedly so that we // avoid triggering the userActivity calls in // PowerManagerService.setPokeLock(). if (duration == mScreenTimeoutDuration) { return; } mScreenTimeoutDuration = duration; updatePokeLock(); } /** * Update the state of the poke lock held by the phone app, * based on the current desired screen timeout and the * current "ignore user activity on touch" flag. */ private void updatePokeLock() { // Caller must take care of the check. This block is purely for safety. if (proximitySensorModeEnabled()) { Log.wtf(LOG_TAG, "PokeLock should not be used when proximity sensor is available on" + " the device."); return; } // This is kind of convoluted, but the basic thing to remember is // that the poke lock just sends a message to the screen to tell // it to stay on for a while. // The default is 0, for a long timeout and should be set that way // when we are heading back into a the keyguard / screen off // state, and also when we're trying to keep the screen alive // while ringing. We'll also want to ignore the cheek events // regardless of the timeout duration. // The short timeout is really used whenever we want to give up // the screen lock, such as when we're in call. int pokeLockSetting = 0; switch (mScreenTimeoutDuration) { case SHORT: // Set the poke lock to timeout the display after a short // timeout (5s). This ensures that the screen goes to sleep // as soon as acceptably possible after we the wake lock // has been released. pokeLockSetting |= LocalPowerManager.POKE_LOCK_SHORT_TIMEOUT; break; case MEDIUM: // Set the poke lock to timeout the display after a medium // timeout (15s). This ensures that the screen goes to sleep // as soon as acceptably possible after we the wake lock // has been released. pokeLockSetting |= LocalPowerManager.POKE_LOCK_MEDIUM_TIMEOUT; break; case DEFAULT: default: // set the poke lock to timeout the display after a long // delay by default. // TODO: it may be nice to be able to disable cheek presses // for long poke locks (emergency dialer, for instance). break; } if (mIgnoreTouchUserActivity) { pokeLockSetting |= LocalPowerManager.POKE_LOCK_IGNORE_TOUCH_EVENTS; } // Send the request try { mPowerManagerService.setPokeLock(pokeLockSetting, mPokeLockToken, LOG_TAG); } catch (RemoteException e) { Log.w(LOG_TAG, "mPowerManagerService.setPokeLock() failed: " + e); } } /** * Controls whether or not the screen is allowed to sleep. * * Once sleep is allowed (WakeState is SLEEP), it will rely on the * settings for the poke lock to determine when to timeout and let * the device sleep {@link PhoneApp#setScreenTimeout}. * * @param ws tells the device to how to wake. */ /* package */ void requestWakeState(WakeState ws) { if (VDBG) Log.d(LOG_TAG, "requestWakeState(" + ws + ")..."); synchronized (this) { if (mWakeState != ws) { switch (ws) { case PARTIAL: // acquire the processor wake lock, and release the FULL // lock if it is being held. mPartialWakeLock.acquire(); if (mWakeLock.isHeld()) { mWakeLock.release(); } break; case FULL: // acquire the full wake lock, and release the PARTIAL // lock if it is being held. mWakeLock.acquire(); if (mPartialWakeLock.isHeld()) { mPartialWakeLock.release(); } break; case SLEEP: default: // release both the PARTIAL and FULL locks. if (mWakeLock.isHeld()) { mWakeLock.release(); } if (mPartialWakeLock.isHeld()) { mPartialWakeLock.release(); } break; } mWakeState = ws; } } } /** * If we are not currently keeping the screen on, then poke the power * manager to wake up the screen for the user activity timeout duration. */ /* package */ void wakeUpScreen() { synchronized (this) { if (mWakeState == WakeState.SLEEP) { if (DBG) Log.d(LOG_TAG, "pulse screen lock"); try { mPowerManagerService.userActivityWithForce(SystemClock.uptimeMillis(), false, true); } catch (RemoteException ex) { // Ignore -- the system process is dead. } } } } /** * Sets the wake state and screen timeout based on the current state * of the phone, and the current state of the in-call UI. * * This method is a "UI Policy" wrapper around * {@link PhoneApp#requestWakeState} and {@link PhoneApp#setScreenTimeout}. * * It's safe to call this method regardless of the state of the Phone * (e.g. whether or not it's idle), and regardless of the state of the * Phone UI (e.g. whether or not the InCallScreen is active.) */ /* package */ void updateWakeState() { Phone.State state = mCM.getState(); // True if the in-call UI is the foreground activity. // (Note this will be false if the screen is currently off, // since in that case *no* activity is in the foreground.) boolean isShowingCallScreen = isShowingCallScreen(); // True if the InCallScreen's DTMF dialer is currently opened. // (Note this does NOT imply whether or not the InCallScreen // itself is visible.) boolean isDialerOpened = (mInCallScreen != null) && mInCallScreen.isDialerOpened(); // True if the speakerphone is in use. (If so, we *always* use // the default timeout. Since the user is obviously not holding // the phone up to his/her face, we don't need to worry about // false touches, and thus don't need to turn the screen off so // aggressively.) // Note that we need to make a fresh call to this method any // time the speaker state changes. (That happens in // PhoneUtils.turnOnSpeaker().) boolean isSpeakerInUse = (state == Phone.State.OFFHOOK) && PhoneUtils.isSpeakerOn(this); // TODO (bug 1440854): The screen timeout *might* also need to // depend on the bluetooth state, but this isn't as clear-cut as // the speaker state (since while using BT it's common for the // user to put the phone straight into a pocket, in which case the // timeout should probably still be short.) if (DBG) Log.d(LOG_TAG, "updateWakeState: callscreen " + isShowingCallScreen + ", dialer " + isDialerOpened + ", speaker " + isSpeakerInUse + "..."); // // (1) Set the screen timeout. // // Note that the "screen timeout" value we determine here is // meaningless if the screen is forced on (see (2) below.) // // Historical note: In froyo and earlier, we checked here for a special // case: the in-call UI being active, the speaker off, and the DTMF dialpad // not visible. In that case, with no touchable UI onscreen at all (for // non-prox-sensor devices at least), we could assume the user was probably // holding the phone up to their face and *not* actually looking at the // screen. So we'd switch to a special screen timeout value // (ScreenTimeoutDuration.MEDIUM), purely to save battery life. // // On current devices, we can rely on the proximity sensor to turn the // screen off in this case, so we use the system-wide default timeout // unconditionally. setScreenTimeout(ScreenTimeoutDuration.DEFAULT); // // (2) Decide whether to force the screen on or not. // // Force the screen to be on if the phone is ringing or dialing, // or if we're displaying the "Call ended" UI for a connection in // the "disconnected" state. // boolean isRinging = (state == Phone.State.RINGING); boolean isDialing = (phone.getForegroundCall().getState() == Call.State.DIALING); boolean showingDisconnectedConnection = PhoneUtils.hasDisconnectedConnections(phone) && isShowingCallScreen; boolean keepScreenOn = isRinging || isDialing || showingDisconnectedConnection; if (DBG) Log.d(LOG_TAG, "updateWakeState: keepScreenOn = " + keepScreenOn + " (isRinging " + isRinging + ", isDialing " + isDialing + ", showingDisc " + showingDisconnectedConnection + ")"); // keepScreenOn == true means we'll hold a full wake lock: requestWakeState(keepScreenOn ? WakeState.FULL : WakeState.SLEEP); } /** * Wrapper around the PowerManagerService.preventScreenOn() API. * This allows the in-call UI to prevent the screen from turning on * even if a subsequent call to updateWakeState() causes us to acquire * a full wake lock. */ /* package */ void preventScreenOn(boolean prevent) { if (VDBG) Log.d(LOG_TAG, "- preventScreenOn(" + prevent + ")..."); try { mPowerManagerService.preventScreenOn(prevent); } catch (RemoteException e) { Log.w(LOG_TAG, "mPowerManagerService.preventScreenOn() failed: " + e); } } /** * Sets or clears the flag that tells the PowerManager that touch * (and cheek) events should NOT be considered "user activity". * * This method is no-op when proximity sensor is available on the device. * * Since the in-call UI is totally insensitive to touch in most * states, we set this flag whenever the InCallScreen is in the * foreground. (Otherwise, repeated unintentional touches could * prevent the device from going to sleep.) * * There *are* some some touch events that really do count as user * activity, though. For those, we need to manually poke the * PowerManager's userActivity method; see pokeUserActivity(). */ /* package */ void setIgnoreTouchUserActivity(boolean ignore) { if (VDBG) Log.d(LOG_TAG, "setIgnoreTouchUserActivity(" + ignore + ")..."); // stick with default timeout if we are using the proximity sensor if (proximitySensorModeEnabled()) { return; } mIgnoreTouchUserActivity = ignore; updatePokeLock(); } /** * Manually pokes the PowerManager's userActivity method. Since we * hold the POKE_LOCK_IGNORE_TOUCH_EVENTS poke lock while * the InCallScreen is active, we need to do this for touch events * that really do count as user activity (like pressing any * onscreen UI elements.) */ /* package */ void pokeUserActivity() { if (VDBG) Log.d(LOG_TAG, "pokeUserActivity()..."); try { mPowerManagerService.userActivity(SystemClock.uptimeMillis(), false); } catch (RemoteException e) { Log.w(LOG_TAG, "mPowerManagerService.userActivity() failed: " + e); } } /** * Set when a new outgoing call is beginning, so we can update * the proximity sensor state. * Cleared when the InCallScreen is no longer in the foreground, * in case the call fails without changing the telephony state. */ /* package */ void setBeginningCall(boolean beginning) { // Note that we are beginning a new call, for proximity sensor support mBeginningCall = beginning; // Update the Proximity sensor based on mBeginningCall state updateProximitySensorMode(mCM.getState()); } /** * Updates the wake lock used to control proximity sensor behavior, * based on the current state of the phone. This method is called * from the CallNotifier on any phone state change. * * On devices that have a proximity sensor, to avoid false touches * during a call, we hold a PROXIMITY_SCREEN_OFF_WAKE_LOCK wake lock * whenever the phone is off hook. (When held, that wake lock causes * the screen to turn off automatically when the sensor detects an * object close to the screen.) * * This method is a no-op for devices that don't have a proximity * sensor. * * Note this method doesn't care if the InCallScreen is the foreground * activity or not. That's because we want the proximity sensor to be * enabled any time the phone is in use, to avoid false cheek events * for whatever app you happen to be running. * * Proximity wake lock will *not* be held if any one of the * conditions is true while on a call: * 1) If the audio is routed via Bluetooth * 2) If a wired headset is connected * 3) if the speaker is ON * 4) If the slider is open(i.e. the hardkeyboard is *not* hidden) * * @param state current state of the phone (see {@link Phone#State}) */ /* package */ void updateProximitySensorMode(Phone.State state) { if (VDBG) Log.d(LOG_TAG, "updateProximitySensorMode: state = " + state); if (proximitySensorModeEnabled()) { synchronized (mProximityWakeLock) { // turn proximity sensor off and turn screen on immediately if // we are using a headset, the keyboard is open, or the device // is being held in a horizontal position. boolean screenOnImmediately = (isHeadsetPlugged() || PhoneUtils.isSpeakerOn(this) || ((mBtHandsfree != null) && mBtHandsfree.isAudioOn()) || mIsHardKeyboardOpen); // We do not keep the screen off when the user is outside in-call screen and we are // horizontal, but we do not force it on when we become horizontal until the // proximity sensor goes negative. boolean horizontal = (mOrientation == AccelerometerListener.ORIENTATION_HORIZONTAL); screenOnImmediately |= !isShowingCallScreenForProximity() && horizontal; // We do not keep the screen off when dialpad is visible, we are horizontal, and // the in-call screen is being shown. // At that moment we're pretty sure users want to use it, instead of letting the // proximity sensor turn off the screen by their hands. boolean dialpadVisible = false; if (mInCallScreen != null) { dialpadVisible = mInCallScreen.getUpdatedInCallControlState().dialpadEnabled && mInCallScreen.getUpdatedInCallControlState().dialpadVisible && isShowingCallScreen(); } screenOnImmediately |= dialpadVisible && horizontal; if (((state == Phone.State.OFFHOOK) || mBeginningCall) && !screenOnImmediately) { // Phone is in use! Arrange for the screen to turn off // automatically when the sensor detects a close object. if (!mProximityWakeLock.isHeld()) { if (DBG) Log.d(LOG_TAG, "updateProximitySensorMode: acquiring..."); mProximityWakeLock.acquire(); } else { if (VDBG) Log.d(LOG_TAG, "updateProximitySensorMode: lock already held."); } } else { // Phone is either idle, or ringing. We don't want any // special proximity sensor behavior in either case. if (mProximityWakeLock.isHeld()) { if (DBG) Log.d(LOG_TAG, "updateProximitySensorMode: releasing..."); // Wait until user has moved the phone away from his head if we are // releasing due to the phone call ending. // Qtherwise, turn screen on immediately int flags = (screenOnImmediately ? 0 : PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE); mProximityWakeLock.release(flags); } else { if (VDBG) { Log.d(LOG_TAG, "updateProximitySensorMode: lock already released."); } } } } } } @Override public void orientationChanged(int orientation) { mOrientation = orientation; updateProximitySensorMode(mCM.getState()); } /** * Notifies the phone app when the phone state changes. * * This method will updates various states inside Phone app (e.g. proximity sensor mode, * accelerometer listener state, update-lock state, etc.) */ /* package */ void updatePhoneState(Phone.State state) { if (state != mLastPhoneState) { mLastPhoneState = state; updateProximitySensorMode(state); // Try to acquire or release UpdateLock. // // Watch out: we don't release the lock here when the screen is still in foreground. // At that time InCallScreen will release it on onPause(). if (state != Phone.State.IDLE) { // UpdateLock is a recursive lock, while we may get "acquire" request twice and // "release" request once for a single call (RINGING + OFFHOOK and IDLE). // We need to manually ensure the lock is just acquired once for each (and this // will prevent other possible buggy situations too). if (!mUpdateLock.isHeld()) { mUpdateLock.acquire(); } } else { if (!isShowingCallScreen()) { if (!mUpdateLock.isHeld()) { mUpdateLock.release(); } } else { // For this case InCallScreen will take care of the release() call. } } if (mAccelerometerListener != null) { // use accelerometer to augment proximity sensor when in call mOrientation = AccelerometerListener.ORIENTATION_UNKNOWN; mAccelerometerListener.enable(state == Phone.State.OFFHOOK); } // clear our beginning call flag mBeginningCall = false; // While we are in call, the in-call screen should dismiss the keyguard. // This allows the user to press Home to go directly home without going through // an insecure lock screen. // But we do not want to do this if there is no active call so we do not // bypass the keyguard if the call is not answered or declined. if (mInCallScreen != null) { mInCallScreen.updateKeyguardPolicy(state == Phone.State.OFFHOOK); } } } /* package */ Phone.State getPhoneState() { return mLastPhoneState; } /** * Returns UpdateLock object. */ /* package */ UpdateLock getUpdateLock() { return mUpdateLock; } /** * @return true if this device supports the "proximity sensor * auto-lock" feature while in-call (see updateProximitySensorMode()). */ /* package */ boolean proximitySensorModeEnabled() { return (mProximityWakeLock != null); } KeyguardManager getKeyguardManager() { return mKeyguardManager; } private void onMMIComplete(AsyncResult r) { if (VDBG) Log.d(LOG_TAG, "onMMIComplete()..."); MmiCode mmiCode = (MmiCode) r.result; PhoneUtils.displayMMIComplete(phone, getInstance(), mmiCode, null, null); } private void initForNewRadioTechnology() { if (DBG) Log.d(LOG_TAG, "initForNewRadioTechnology..."); if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) { // Create an instance of CdmaPhoneCallState and initialize it to IDLE cdmaPhoneCallState = new CdmaPhoneCallState(); cdmaPhoneCallState.CdmaPhoneCallStateInit(); } if (TelephonyCapabilities.supportsOtasp(phone)) { //create instances of CDMA OTA data classes if (cdmaOtaProvisionData == null) { cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData(); } if (cdmaOtaConfigData == null) { cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData(); } if (cdmaOtaScreenState == null) { cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState(); } if (cdmaOtaInCallScreenUiState == null) { cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState(); } } else { //Clean up OTA data in GSM/UMTS. It is valid only for CDMA clearOtaState(); } ringer.updateRingerContextAfterRadioTechnologyChange(this.phone); notifier.updateCallNotifierRegistrationsAfterRadioTechnologyChange(); if (mBtHandsfree != null) { mBtHandsfree.updateBtHandsfreeAfterRadioTechnologyChange(); } if (mInCallScreen != null) { mInCallScreen.updateAfterRadioTechnologyChange(); } // Update registration for ICC status after radio technology change IccCard sim = phone.getIccCard(); if (sim != null) { if (DBG) Log.d(LOG_TAG, "Update registration for ICC status..."); //Register all events new to the new active phone sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null); } } /** * @return true if a wired headset is currently plugged in. * * @see Intent.ACTION_HEADSET_PLUG (which we listen for in mReceiver.onReceive()) */ boolean isHeadsetPlugged() { return mIsHeadsetPlugged; } /** * @return true if the onscreen UI should currently be showing the * special "bluetooth is active" indication in a couple of places (in * which UI elements turn blue and/or show the bluetooth logo.) * * This depends on the BluetoothHeadset state *and* the current * telephony state; see shouldShowBluetoothIndication(). * * @see CallCard * @see NotificationMgr.updateInCallNotification */ /* package */ boolean showBluetoothIndication() { return mShowBluetoothIndication; } /** * Recomputes the mShowBluetoothIndication flag based on the current * bluetooth state and current telephony state. * * This needs to be called any time the bluetooth headset state or the * telephony state changes. * * @param forceUiUpdate if true, force the UI elements that care * about this flag to update themselves. */ /* package */ void updateBluetoothIndication(boolean forceUiUpdate) { mShowBluetoothIndication = shouldShowBluetoothIndication(mBluetoothHeadsetState, mBluetoothHeadsetAudioState, mCM); if (forceUiUpdate) { // Post Handler messages to the various components that might // need to be refreshed based on the new state. if (isShowingCallScreen()) mInCallScreen.requestUpdateBluetoothIndication(); if (DBG) Log.d (LOG_TAG, "- updating in-call notification for BT state change..."); mHandler.sendEmptyMessage(EVENT_UPDATE_INCALL_NOTIFICATION); } // Update the Proximity sensor based on Bluetooth audio state updateProximitySensorMode(mCM.getState()); } /** * UI policy helper function for the couple of places in the UI that * have some way of indicating that "bluetooth is in use." * * @return true if the onscreen UI should indicate that "bluetooth is in use", * based on the specified bluetooth headset state, and the * current state of the phone. * @see showBluetoothIndication() */ private static boolean shouldShowBluetoothIndication(int bluetoothState, int bluetoothAudioState, CallManager cm) { // We want the UI to indicate that "bluetooth is in use" in two // slightly different cases: // // (a) The obvious case: if a bluetooth headset is currently in // use for an ongoing call. // // (b) The not-so-obvious case: if an incoming call is ringing, // and we expect that audio *will* be routed to a bluetooth // headset once the call is answered. switch (cm.getState()) { case OFFHOOK: // This covers normal active calls, and also the case if // the foreground call is DIALING or ALERTING. In this // case, bluetooth is considered "active" if a headset // is connected *and* audio is being routed to it. return ((bluetoothState == BluetoothHeadset.STATE_CONNECTED) && (bluetoothAudioState == BluetoothHeadset.STATE_AUDIO_CONNECTED)); case RINGING: // If an incoming call is ringing, we're *not* yet routing // audio to the headset (since there's no in-call audio // yet!) In this case, if a bluetooth headset is // connected at all, we assume that it'll become active // once the user answers the phone. return (bluetoothState == BluetoothHeadset.STATE_CONNECTED); default: // Presumably IDLE return false; } } /** * Receiver for misc intent broadcasts the Phone app cares about. */ private class PhoneAppBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) { boolean enabled = System.getInt(getContentResolver(), System.AIRPLANE_MODE_ON, 0) == 0; phone.setRadioPower(enabled); } else if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) { mBluetoothHeadsetState = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, BluetoothHeadset.STATE_DISCONNECTED); if (VDBG) Log.d(LOG_TAG, "mReceiver: HEADSET_STATE_CHANGED_ACTION"); if (VDBG) Log.d(LOG_TAG, "==> new state: " + mBluetoothHeadsetState); updateBluetoothIndication(true); // Also update any visible UI if necessary } else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) { mBluetoothHeadsetAudioState = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, BluetoothHeadset.STATE_AUDIO_DISCONNECTED); if (VDBG) Log.d(LOG_TAG, "mReceiver: HEADSET_AUDIO_STATE_CHANGED_ACTION"); if (VDBG) Log.d(LOG_TAG, "==> new state: " + mBluetoothHeadsetAudioState); updateBluetoothIndication(true); // Also update any visible UI if necessary } else if (action.equals(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED)) { if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_ANY_DATA_CONNECTION_STATE_CHANGED"); if (VDBG) Log.d(LOG_TAG, "- state: " + intent.getStringExtra(Phone.STATE_KEY)); if (VDBG) Log.d(LOG_TAG, "- reason: " + intent.getStringExtra(Phone.STATE_CHANGE_REASON_KEY)); // The "data disconnected due to roaming" notification is shown // if (a) you have the "data roaming" feature turned off, and // (b) you just lost data connectivity because you're roaming. boolean disconnectedDueToRoaming = !phone.getDataRoamingEnabled() && "DISCONNECTED".equals(intent.getStringExtra(Phone.STATE_KEY)) && Phone.REASON_ROAMING_ON.equals( intent.getStringExtra(Phone.STATE_CHANGE_REASON_KEY)); mHandler.sendEmptyMessage(disconnectedDueToRoaming ? EVENT_DATA_ROAMING_DISCONNECTED : EVENT_DATA_ROAMING_OK); } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) { if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_HEADSET_PLUG"); if (VDBG) Log.d(LOG_TAG, " state: " + intent.getIntExtra("state", 0)); if (VDBG) Log.d(LOG_TAG, " name: " + intent.getStringExtra("name")); mIsHeadsetPlugged = (intent.getIntExtra("state", 0) == 1); mHandler.sendMessage(mHandler.obtainMessage(EVENT_WIRED_HEADSET_PLUG, 0)); } else if ((action.equals(TelephonyIntents.ACTION_SIM_STATE_CHANGED)) && (mPUKEntryActivity != null)) { // if an attempt to un-PUK-lock the device was made, while we're // receiving this state change notification, notify the handler. // NOTE: This is ONLY triggered if an attempt to un-PUK-lock has // been attempted. mHandler.sendMessage(mHandler.obtainMessage(EVENT_SIM_STATE_CHANGED, intent.getStringExtra(IccCard.INTENT_KEY_ICC_STATE))); } else if (action.equals(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED)) { String newPhone = intent.getStringExtra(Phone.PHONE_NAME_KEY); Log.d(LOG_TAG, "Radio technology switched. Now " + newPhone + " is active."); initForNewRadioTechnology(); } else if (action.equals(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED)) { handleServiceStateChanged(intent); } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) { if (TelephonyCapabilities.supportsEcm(phone)) { Log.d(LOG_TAG, "Emergency Callback Mode arrived in PhoneApp."); // Start Emergency Callback Mode service if (intent.getBooleanExtra("phoneinECMState", false)) { context.startService(new Intent(context, EmergencyCallbackModeService.class)); } } else { // It doesn't make sense to get ACTION_EMERGENCY_CALLBACK_MODE_CHANGED // on a device that doesn't support ECM in the first place. Log.e(LOG_TAG, "Got ACTION_EMERGENCY_CALLBACK_MODE_CHANGED, " + "but ECM isn't supported for phone: " + phone.getPhoneName()); } } else if (action.equals(Intent.ACTION_DOCK_EVENT)) { mDockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED); if (VDBG) Log.d(LOG_TAG, "ACTION_DOCK_EVENT -> mDockState = " + mDockState); mHandler.sendMessage(mHandler.obtainMessage(EVENT_DOCK_STATE_CHANGED, 0)); } else if (action.equals(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION)) { mPreferredTtyMode = intent.getIntExtra(TtyIntent.TTY_PREFFERED_MODE, Phone.TTY_MODE_OFF); if (VDBG) Log.d(LOG_TAG, "mReceiver: TTY_PREFERRED_MODE_CHANGE_ACTION"); if (VDBG) Log.d(LOG_TAG, " mode: " + mPreferredTtyMode); mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0)); } else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) { int ringerMode = intent.getIntExtra(AudioManager.EXTRA_RINGER_MODE, AudioManager.RINGER_MODE_NORMAL); if (ringerMode == AudioManager.RINGER_MODE_SILENT) { notifier.silenceRinger(); } } else if (action.equals(Intent.ACTION_SCREEN_OFF) || action.equals(Intent.ACTION_SCREEN_ON)) { if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_SCREEN_OFF / ACTION_SCREEN_ON"); /* * Disable Accelerometer Listener while in-call and the screen is off. * This is done to ensure that power consumption is kept to a minimum * in such a scenario */ if (mAccelerometerListener != null) { mAccelerometerListener.enable(mLastPhoneState == Phone.State.OFFHOOK && action.equals(Intent.ACTION_SCREEN_ON)); } } } } /** * Broadcast receiver for the ACTION_MEDIA_BUTTON broadcast intent. * * This functionality isn't lumped in with the other intents in * PhoneAppBroadcastReceiver because we instantiate this as a totally * separate BroadcastReceiver instance, since we need to manually * adjust its IntentFilter's priority (to make sure we get these * intents *before* the media player.) */ private class MediaButtonBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT); if (VDBG) Log.d(LOG_TAG, "MediaButtonBroadcastReceiver.onReceive()... event = " + event); if ((event != null) && (event.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK)) { if (VDBG) Log.d(LOG_TAG, "MediaButtonBroadcastReceiver: HEADSETHOOK"); boolean consumed = PhoneUtils.handleHeadsetHook(phone, event); if (VDBG) Log.d(LOG_TAG, "==> handleHeadsetHook(): consumed = " + consumed); if (consumed) { // If a headset is attached and the press is consumed, also update // any UI items (such as an InCallScreen mute button) that may need to // be updated if their state changed. updateInCallScreen(); // Has no effect if the InCallScreen isn't visible abortBroadcast(); } } else { if (mCM.getState() != Phone.State.IDLE) { // If the phone is anything other than completely idle, // then we consume and ignore any media key events, // Otherwise it is too easy to accidentally start // playing music while a phone call is in progress. if (VDBG) Log.d(LOG_TAG, "MediaButtonBroadcastReceiver: consumed"); abortBroadcast(); } } } } /** * Accepts broadcast Intents which will be prepared by {@link NotificationMgr} and thus * sent from framework's notification mechanism (which is outside Phone context). * This should be visible from outside, but shouldn't be in "exported" state. * * TODO: If possible merge this into PhoneAppBroadcastReceiver. */ public static class NotificationBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // TODO: use "if (VDBG)" here. Log.d(LOG_TAG, "Broadcast from Notification: " + action); if (action.equals(ACTION_HANG_UP_ONGOING_CALL)) { PhoneUtils.hangup(PhoneApp.getInstance().mCM); } else if (action.equals(ACTION_CALL_BACK_FROM_NOTIFICATION)) { // Collapse the expanded notification and the notification item itself. closeSystemDialogs(context); clearMissedCallNotification(context); Intent callIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, intent.getData()); callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); context.startActivity(callIntent); } else if (action.equals(ACTION_SEND_SMS_FROM_NOTIFICATION)) { // Collapse the expanded notification and the notification item itself. closeSystemDialogs(context); clearMissedCallNotification(context); Intent smsIntent = new Intent(Intent.ACTION_SENDTO, intent.getData()); smsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(smsIntent); } else { Log.w(LOG_TAG, "Received hang-up request from notification," + " but there's no call the system can hang up."); } } private void closeSystemDialogs(Context context) { Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); context.sendBroadcast(intent); } private void clearMissedCallNotification(Context context) { Intent clearIntent = new Intent(context, ClearMissedCallsService.class); clearIntent.setAction(ClearMissedCallsService.ACTION_CLEAR_MISSED_CALLS); context.startService(clearIntent); } } private void handleServiceStateChanged(Intent intent) { /** * This used to handle updating EriTextWidgetProvider this routine * and and listening for ACTION_SERVICE_STATE_CHANGED intents could * be removed. But leaving just in case it might be needed in the near * future. */ // If service just returned, start sending out the queued messages ServiceState ss = ServiceState.newFromBundle(intent.getExtras()); if (ss != null) { int state = ss.getState(); notificationMgr.updateNetworkSelection(state); } } public boolean isOtaCallInActiveState() { boolean otaCallActive = false; if (mInCallScreen != null) { otaCallActive = mInCallScreen.isOtaCallInActiveState(); } if (VDBG) Log.d(LOG_TAG, "- isOtaCallInActiveState " + otaCallActive); return otaCallActive; } public boolean isOtaCallInEndState() { boolean otaCallEnded = false; if (mInCallScreen != null) { otaCallEnded = mInCallScreen.isOtaCallInEndState(); } if (VDBG) Log.d(LOG_TAG, "- isOtaCallInEndState " + otaCallEnded); return otaCallEnded; } // it is safe to call clearOtaState() even if the InCallScreen isn't active public void clearOtaState() { if (DBG) Log.d(LOG_TAG, "- clearOtaState ..."); if ((mInCallScreen != null) && (otaUtils != null)) { otaUtils.cleanOtaScreen(true); if (DBG) Log.d(LOG_TAG, " - clearOtaState clears OTA screen"); } } // it is safe to call dismissOtaDialogs() even if the InCallScreen isn't active public void dismissOtaDialogs() { if (DBG) Log.d(LOG_TAG, "- dismissOtaDialogs ..."); if ((mInCallScreen != null) && (otaUtils != null)) { otaUtils.dismissAllOtaDialogs(); if (DBG) Log.d(LOG_TAG, " - dismissOtaDialogs clears OTA dialogs"); } } // it is safe to call clearInCallScreenMode() even if the InCallScreen isn't active public void clearInCallScreenMode() { if (DBG) Log.d(LOG_TAG, "- clearInCallScreenMode ..."); if (mInCallScreen != null) { mInCallScreen.resetInCallScreenMode(); } } /** * Force the in-call UI to refresh itself, if it's currently visible. * * This method can be used any time there's a state change anywhere in * the phone app that needs to be reflected in the onscreen UI. * * Note that it's *not* necessary to manually refresh the in-call UI * (via this method) for regular telephony state changes like * DIALING -> ALERTING -> ACTIVE, since the InCallScreen already * listens for those state changes itself. * * This method does *not* force the in-call UI to come up if it's not * already visible. To do that, use displayCallScreen(). */ /* package */ void updateInCallScreen() { if (DBG) Log.d(LOG_TAG, "- updateInCallScreen()..."); if (mInCallScreen != null) { // Post an updateScreen() request. Note that the // updateScreen() call will end up being a no-op if the // InCallScreen isn't the foreground activity. mInCallScreen.requestUpdateScreen(); } } private void handleQueryTTYModeResponse(Message msg) { AsyncResult ar = (AsyncResult) msg.obj; if (ar.exception != null) { if (DBG) Log.d(LOG_TAG, "handleQueryTTYModeResponse: Error getting TTY state."); } else { if (DBG) Log.d(LOG_TAG, "handleQueryTTYModeResponse: TTY enable state successfully queried."); int ttymode = ((int[]) ar.result)[0]; if (DBG) Log.d(LOG_TAG, "handleQueryTTYModeResponse:ttymode=" + ttymode); Intent ttyModeChanged = new Intent(TtyIntent.TTY_ENABLED_CHANGE_ACTION); ttyModeChanged.putExtra("ttyEnabled", ttymode != Phone.TTY_MODE_OFF); sendBroadcast(ttyModeChanged); String audioTtyMode; switch (ttymode) { case Phone.TTY_MODE_FULL: audioTtyMode = "tty_full"; break; case Phone.TTY_MODE_VCO: audioTtyMode = "tty_vco"; break; case Phone.TTY_MODE_HCO: audioTtyMode = "tty_hco"; break; case Phone.TTY_MODE_OFF: default: audioTtyMode = "tty_off"; break; } AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); audioManager.setParameters("tty_mode="+audioTtyMode); } } private void handleSetTTYModeResponse(Message msg) { AsyncResult ar = (AsyncResult) msg.obj; if (ar.exception != null) { if (DBG) Log.d (LOG_TAG, "handleSetTTYModeResponse: Error setting TTY mode, ar.exception" + ar.exception); } phone.queryTTYMode(mHandler.obtainMessage(EVENT_TTY_MODE_GET)); } /* package */ void clearUserActivityTimeout() { try { mPowerManagerService.clearUserActivityTimeout(SystemClock.uptimeMillis(), 10*1000 /* 10 sec */); } catch (RemoteException ex) { // System process is dead. } } /** * "Call origin" may be used by Contacts app to specify where the phone call comes from. * Currently, the only permitted value for this extra is {@link #ALLOWED_EXTRA_CALL_ORIGIN}. * Any other value will be ignored, to make sure that malicious apps can't trick the in-call * UI into launching some random other app after a call ends. * * TODO: make this more generic. Note that we should let the "origin" specify its package * while we are now assuming it is "com.android.contacts" */ public static final String EXTRA_CALL_ORIGIN = "com.android.phone.CALL_ORIGIN"; private static final String DEFAULT_CALL_ORIGIN_PACKAGE = "com.android.contacts"; private static final String ALLOWED_EXTRA_CALL_ORIGIN = "com.android.contacts.activities.DialtactsActivity"; /** * Used to determine if the preserved call origin is fresh enough. */ private static final long CALL_ORIGIN_EXPIRATION_MILLIS = 30 * 1000; public void setLatestActiveCallOrigin(String callOrigin) { inCallUiState.latestActiveCallOrigin = callOrigin; if (callOrigin != null) { inCallUiState.latestActiveCallOriginTimeStamp = SystemClock.elapsedRealtime(); } else { inCallUiState.latestActiveCallOriginTimeStamp = 0; } } /** * Reset call origin depending on its timestamp. * * See if the current call origin preserved by the app is fresh enough or not. If it is, * previous call origin will be used as is. If not, call origin will be reset. * * This will be effective especially for 3rd party apps which want to bypass phone calls with * their own telephone lines. In that case Phone app may finish the phone call once and make * another for the external apps, which will drop call origin information in Intent. * Even in that case we are sure the second phone call should be initiated just after the first * phone call, so here we restore it from the previous information iff the second call is done * fairly soon. */ public void resetLatestActiveCallOrigin() { final long callOriginTimestamp = inCallUiState.latestActiveCallOriginTimeStamp; final long currentTimestamp = SystemClock.elapsedRealtime(); if (VDBG) { Log.d(LOG_TAG, "currentTimeMillis: " + currentTimestamp + ", saved timestamp for call origin: " + callOriginTimestamp); } if (inCallUiState.latestActiveCallOriginTimeStamp > 0 && (currentTimestamp - callOriginTimestamp < CALL_ORIGIN_EXPIRATION_MILLIS)) { if (VDBG) { Log.d(LOG_TAG, "Resume previous call origin (" + inCallUiState.latestActiveCallOrigin + ")"); } // Do nothing toward call origin itself but update the timestamp just in case. inCallUiState.latestActiveCallOriginTimeStamp = currentTimestamp; } else { if (VDBG) Log.d(LOG_TAG, "Drop previous call origin and set the current one to null"); setLatestActiveCallOrigin(null); } } /** * @return Intent which will be used when in-call UI is shown and the phone call is hang up. * By default CallLog screen will be introduced, but the destination may change depending on * its latest call origin state. */ public Intent createPhoneEndIntentUsingCallOrigin() { if (TextUtils.equals(inCallUiState.latestActiveCallOrigin, ALLOWED_EXTRA_CALL_ORIGIN)) { if (VDBG) Log.d(LOG_TAG, "Valid latestActiveCallOrigin(" + inCallUiState.latestActiveCallOrigin + ") was found. " + "Go back to the previous screen."); // Right now we just launch the Activity which launched in-call UI. Note that we're // assuming the origin is from "com.android.contacts", which may be incorrect in the // future. final Intent intent = new Intent(); intent.setClassName(DEFAULT_CALL_ORIGIN_PACKAGE, inCallUiState.latestActiveCallOrigin); return intent; } else { if (VDBG) Log.d(LOG_TAG, "Current latestActiveCallOrigin (" + inCallUiState.latestActiveCallOrigin + ") is not valid. " + "Just use CallLog as a default destination."); return PhoneApp.createCallLogIntent(); } } }
true
true
public void onCreate() { if (VDBG) Log.v(LOG_TAG, "onCreate()..."); ContentResolver resolver = getContentResolver(); // Cache the "voice capable" flag. // This flag currently comes from a resource (which is // overrideable on a per-product basis): sVoiceCapable = getResources().getBoolean(com.android.internal.R.bool.config_voice_capable); // ...but this might eventually become a PackageManager "system // feature" instead, in which case we'd do something like: // sVoiceCapable = // getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY_VOICE_CALLS); if (phone == null) { // Initialize the telephony framework PhoneFactory.makeDefaultPhones(this); // Get the default phone phone = PhoneFactory.getDefaultPhone(); // Start TelephonyDebugService After the default phone is created. Intent intent = new Intent(this, TelephonyDebugService.class); startService(intent); mCM = CallManager.getInstance(); mCM.registerPhone(phone); // Create the NotificationMgr singleton, which is used to display // status bar icons and control other status bar behavior. notificationMgr = NotificationMgr.init(this); phoneMgr = PhoneInterfaceManager.init(this, phone); mHandler.sendEmptyMessage(EVENT_START_SIP_SERVICE); int phoneType = phone.getPhoneType(); if (phoneType == Phone.PHONE_TYPE_CDMA) { // Create an instance of CdmaPhoneCallState and initialize it to IDLE cdmaPhoneCallState = new CdmaPhoneCallState(); cdmaPhoneCallState.CdmaPhoneCallStateInit(); } if (BluetoothAdapter.getDefaultAdapter() != null) { // Start BluetoothHandsree even if device is not voice capable. // The device can still support VOIP. mBtHandsfree = BluetoothHandsfree.init(this, mCM); startService(new Intent(this, BluetoothHeadsetService.class)); } else { // Device is not bluetooth capable mBtHandsfree = null; } ringer = Ringer.init(this); // before registering for phone state changes PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, LOG_TAG); // lock used to keep the processor awake, when we don't care for the display. mPartialWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, LOG_TAG); // Wake lock used to control proximity sensor behavior. if ((pm.getSupportedWakeLockFlags() & PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) != 0x0) { mProximityWakeLock = pm.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, LOG_TAG); } if (DBG) Log.d(LOG_TAG, "onCreate: mProximityWakeLock: " + mProximityWakeLock); // create mAccelerometerListener only if we are using the proximity sensor if (proximitySensorModeEnabled()) { mAccelerometerListener = new AccelerometerListener(this, this); } mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); // get a handle to the service so that we can use it later when we // want to set the poke lock. mPowerManagerService = IPowerManager.Stub.asInterface( ServiceManager.getService("power")); // Get UpdateLock to suppress system-update related events (e.g. dialog show-up) // during phone calls. mUpdateLock = new UpdateLock("phone"); if (DBG) Log.d(LOG_TAG, "onCreate: mUpdateLock: " + mUpdateLock); // Create the CallController singleton, which is the interface // to the telephony layer for user-initiated telephony functionality // (like making outgoing calls.) callController = CallController.init(this); // ...and also the InCallUiState instance, used by the CallController to // keep track of some "persistent state" of the in-call UI. inCallUiState = InCallUiState.init(this); // Create the CallerInfoCache singleton, which remembers custom ring tone and // send-to-voicemail settings. // // The asynchronous caching will start just after this call. callerInfoCache = CallerInfoCache.init(this); // Create the CallNotifer singleton, which handles // asynchronous events from the telephony layer (like // launching the incoming-call UI when an incoming call comes // in.) notifier = CallNotifier.init(this, phone, ringer, mBtHandsfree, new CallLogAsync()); // register for ICC status IccCard sim = phone.getIccCard(); if (sim != null) { if (VDBG) Log.v(LOG_TAG, "register for ICC status"); sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null); } // register for MMI/USSD mCM.registerForMmiComplete(mHandler, MMI_COMPLETE, null); // register connection tracking to PhoneUtils PhoneUtils.initializeConnectionHandler(mCM); // Read platform settings for TTY feature mTtyEnabled = getResources().getBoolean(R.bool.tty_enabled); // Register for misc other intent broadcasts. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED); intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED); intentFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED); intentFilter.addAction(Intent.ACTION_HEADSET_PLUG); intentFilter.addAction(Intent.ACTION_DOCK_EVENT); intentFilter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED); intentFilter.addAction(Intent.ACTION_SCREEN_OFF); intentFilter.addAction(Intent.ACTION_SCREEN_ON); if (mTtyEnabled) { intentFilter.addAction(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION); } intentFilter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); registerReceiver(mReceiver, intentFilter); // Use a separate receiver for ACTION_MEDIA_BUTTON broadcasts, // since we need to manually adjust its priority (to make sure // we get these intents *before* the media player.) IntentFilter mediaButtonIntentFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON); // TODO verify the independent priority doesn't need to be handled thanks to the // private intent handler registration // Make sure we're higher priority than the media player's // MediaButtonIntentReceiver (which currently has the default // priority of zero; see apps/Music/AndroidManifest.xml.) mediaButtonIntentFilter.setPriority(1); // registerReceiver(mMediaButtonReceiver, mediaButtonIntentFilter); // register the component so it gets priority for calls AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); am.registerMediaButtonEventReceiverForCalls(new ComponentName(this.getPackageName(), MediaButtonBroadcastReceiver.class.getName())); //set the default values for the preferences in the phone. PreferenceManager.setDefaultValues(this, R.xml.network_setting, false); PreferenceManager.setDefaultValues(this, R.xml.call_feature_setting, false); // Make sure the audio mode (along with some // audio-mode-related state of our own) is initialized // correctly, given the current state of the phone. PhoneUtils.setAudioMode(mCM); } if (TelephonyCapabilities.supportsOtasp(phone)) { cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData(); cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData(); cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState(); cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState(); } // XXX pre-load the SimProvider so that it's ready resolver.getType(Uri.parse("content://icc/adn")); // start with the default value to set the mute state. mShouldRestoreMuteOnInCallResume = false; // TODO: Register for Cdma Information Records // phone.registerCdmaInformationRecord(mHandler, EVENT_UNSOL_CDMA_INFO_RECORD, null); // Read TTY settings and store it into BP NV. // AP owns (i.e. stores) the TTY setting in AP settings database and pushes the setting // to BP at power up (BP does not need to make the TTY setting persistent storage). // This way, there is a single owner (i.e AP) for the TTY setting in the phone. if (mTtyEnabled) { mPreferredTtyMode = android.provider.Settings.Secure.getInt( phone.getContext().getContentResolver(), android.provider.Settings.Secure.PREFERRED_TTY_MODE, Phone.TTY_MODE_OFF); mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0)); } // Read HAC settings and configure audio hardware if (getResources().getBoolean(R.bool.hac_enabled)) { int hac = android.provider.Settings.System.getInt(phone.getContext().getContentResolver(), android.provider.Settings.System.HEARING_AID, 0); AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); audioManager.setParameter(CallFeaturesSetting.HAC_KEY, hac != 0 ? CallFeaturesSetting.HAC_VAL_ON : CallFeaturesSetting.HAC_VAL_OFF); } }
public void onCreate() { if (VDBG) Log.v(LOG_TAG, "onCreate()..."); ContentResolver resolver = getContentResolver(); // Cache the "voice capable" flag. // This flag currently comes from a resource (which is // overrideable on a per-product basis): sVoiceCapable = getResources().getBoolean(com.android.internal.R.bool.config_voice_capable); // ...but this might eventually become a PackageManager "system // feature" instead, in which case we'd do something like: // sVoiceCapable = // getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY_VOICE_CALLS); if (phone == null) { // Initialize the telephony framework PhoneFactory.makeDefaultPhones(this); // Get the default phone phone = PhoneFactory.getDefaultPhone(); // Start TelephonyDebugService After the default phone is created. Intent intent = new Intent(this, TelephonyDebugService.class); startService(intent); mCM = CallManager.getInstance(); mCM.registerPhone(phone); // Create the NotificationMgr singleton, which is used to display // status bar icons and control other status bar behavior. notificationMgr = NotificationMgr.init(this); phoneMgr = PhoneInterfaceManager.init(this, phone); mHandler.sendEmptyMessage(EVENT_START_SIP_SERVICE); int phoneType = phone.getPhoneType(); if (phoneType == Phone.PHONE_TYPE_CDMA) { // Create an instance of CdmaPhoneCallState and initialize it to IDLE cdmaPhoneCallState = new CdmaPhoneCallState(); cdmaPhoneCallState.CdmaPhoneCallStateInit(); } if (BluetoothAdapter.getDefaultAdapter() != null) { // Start BluetoothHandsree even if device is not voice capable. // The device can still support VOIP. mBtHandsfree = BluetoothHandsfree.init(this, mCM); startService(new Intent(this, BluetoothHeadsetService.class)); } else { // Device is not bluetooth capable mBtHandsfree = null; } ringer = Ringer.init(this); // before registering for phone state changes PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, LOG_TAG); // lock used to keep the processor awake, when we don't care for the display. mPartialWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, LOG_TAG); // Wake lock used to control proximity sensor behavior. if ((pm.getSupportedWakeLockFlags() & PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) != 0x0) { mProximityWakeLock = pm.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, LOG_TAG); } if (DBG) Log.d(LOG_TAG, "onCreate: mProximityWakeLock: " + mProximityWakeLock); // create mAccelerometerListener only if we are using the proximity sensor if (proximitySensorModeEnabled()) { mAccelerometerListener = new AccelerometerListener(this, this); } mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); // get a handle to the service so that we can use it later when we // want to set the poke lock. mPowerManagerService = IPowerManager.Stub.asInterface( ServiceManager.getService("power")); // Get UpdateLock to suppress system-update related events (e.g. dialog show-up) // during phone calls. mUpdateLock = new UpdateLock("phone"); if (DBG) Log.d(LOG_TAG, "onCreate: mUpdateLock: " + mUpdateLock); // Create the CallController singleton, which is the interface // to the telephony layer for user-initiated telephony functionality // (like making outgoing calls.) callController = CallController.init(this); // ...and also the InCallUiState instance, used by the CallController to // keep track of some "persistent state" of the in-call UI. inCallUiState = InCallUiState.init(this); // Create the CallerInfoCache singleton, which remembers custom ring tone and // send-to-voicemail settings. // // The asynchronous caching will start just after this call. callerInfoCache = CallerInfoCache.init(this); // Create the CallNotifer singleton, which handles // asynchronous events from the telephony layer (like // launching the incoming-call UI when an incoming call comes // in.) notifier = CallNotifier.init(this, phone, ringer, mBtHandsfree, new CallLogAsync()); // register for ICC status IccCard sim = phone.getIccCard(); if (sim != null) { if (VDBG) Log.v(LOG_TAG, "register for ICC status"); sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null); } // register for MMI/USSD mCM.registerForMmiComplete(mHandler, MMI_COMPLETE, null); // register connection tracking to PhoneUtils PhoneUtils.initializeConnectionHandler(mCM); // Read platform settings for TTY feature mTtyEnabled = getResources().getBoolean(R.bool.tty_enabled); // Register for misc other intent broadcasts. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED); intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED); intentFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED); intentFilter.addAction(Intent.ACTION_HEADSET_PLUG); intentFilter.addAction(Intent.ACTION_DOCK_EVENT); intentFilter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED); intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED); intentFilter.addAction(Intent.ACTION_SCREEN_OFF); intentFilter.addAction(Intent.ACTION_SCREEN_ON); if (mTtyEnabled) { intentFilter.addAction(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION); } intentFilter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); registerReceiver(mReceiver, intentFilter); // Use a separate receiver for ACTION_MEDIA_BUTTON broadcasts, // since we need to manually adjust its priority (to make sure // we get these intents *before* the media player.) IntentFilter mediaButtonIntentFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON); // TODO verify the independent priority doesn't need to be handled thanks to the // private intent handler registration // Make sure we're higher priority than the media player's // MediaButtonIntentReceiver (which currently has the default // priority of zero; see apps/Music/AndroidManifest.xml.) mediaButtonIntentFilter.setPriority(1); // registerReceiver(mMediaButtonReceiver, mediaButtonIntentFilter); // register the component so it gets priority for calls AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); am.registerMediaButtonEventReceiverForCalls(new ComponentName(this.getPackageName(), MediaButtonBroadcastReceiver.class.getName())); //set the default values for the preferences in the phone. PreferenceManager.setDefaultValues(this, R.xml.network_setting, false); PreferenceManager.setDefaultValues(this, R.xml.call_feature_setting, false); // Make sure the audio mode (along with some // audio-mode-related state of our own) is initialized // correctly, given the current state of the phone. PhoneUtils.setAudioMode(mCM); } if (TelephonyCapabilities.supportsOtasp(phone)) { cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData(); cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData(); cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState(); cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState(); } // XXX pre-load the SimProvider so that it's ready resolver.getType(Uri.parse("content://icc/adn")); // start with the default value to set the mute state. mShouldRestoreMuteOnInCallResume = false; // TODO: Register for Cdma Information Records // phone.registerCdmaInformationRecord(mHandler, EVENT_UNSOL_CDMA_INFO_RECORD, null); // Read TTY settings and store it into BP NV. // AP owns (i.e. stores) the TTY setting in AP settings database and pushes the setting // to BP at power up (BP does not need to make the TTY setting persistent storage). // This way, there is a single owner (i.e AP) for the TTY setting in the phone. if (mTtyEnabled) { mPreferredTtyMode = android.provider.Settings.Secure.getInt( phone.getContext().getContentResolver(), android.provider.Settings.Secure.PREFERRED_TTY_MODE, Phone.TTY_MODE_OFF); mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0)); } // Read HAC settings and configure audio hardware if (getResources().getBoolean(R.bool.hac_enabled)) { int hac = android.provider.Settings.System.getInt(phone.getContext().getContentResolver(), android.provider.Settings.System.HEARING_AID, 0); AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); audioManager.setParameter(CallFeaturesSetting.HAC_KEY, hac != 0 ? CallFeaturesSetting.HAC_VAL_ON : CallFeaturesSetting.HAC_VAL_OFF); } }
diff --git a/taskflows/interSliceTransfer/server/src/de/zib/gndms/taskflows/interslicetransfer/server/logic/InterSliceTransferTaskAction.java b/taskflows/interSliceTransfer/server/src/de/zib/gndms/taskflows/interslicetransfer/server/logic/InterSliceTransferTaskAction.java index dee029a2..cdcc3fe8 100644 --- a/taskflows/interSliceTransfer/server/src/de/zib/gndms/taskflows/interslicetransfer/server/logic/InterSliceTransferTaskAction.java +++ b/taskflows/interSliceTransfer/server/src/de/zib/gndms/taskflows/interslicetransfer/server/logic/InterSliceTransferTaskAction.java @@ -1,298 +1,300 @@ package de.zib.gndms.taskflows.interslicetransfer.server.logic; /* * Copyright 2008-2011 Zuse Institute Berlin (ZIB) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import de.zib.gndms.common.kit.security.CustomSSLContextRequestFactory; import de.zib.gndms.common.kit.security.SetupSSL; import de.zib.gndms.common.rest.Specifier; import de.zib.gndms.common.rest.UriFactory; import de.zib.gndms.gndmc.dspace.SliceClient; import de.zib.gndms.gndmc.dspace.SubspaceClient; import de.zib.gndms.infra.GridConfig; import de.zib.gndms.logic.model.gorfx.TaskFlowAction; import de.zib.gndms.model.gorfx.types.DelegatingOrder; import de.zib.gndms.model.gorfx.types.TaskState; import de.zib.gndms.neomodel.common.Dao; import de.zib.gndms.neomodel.common.Session; import de.zib.gndms.neomodel.gorfx.Task; import de.zib.gndms.neomodel.gorfx.Taskling; import de.zib.gndms.taskflows.filetransfer.client.model.FileTransferResult; import de.zib.gndms.taskflows.filetransfer.server.logic.FileTransferTaskAction; import de.zib.gndms.taskflows.interslicetransfer.client.InterSliceTransferMeta; import de.zib.gndms.taskflows.interslicetransfer.client.model.InterSliceTransferOrder; import de.zib.gndms.taskflows.interslicetransfer.client.model.InterSliceTransferResult; import org.jetbrains.annotations.NotNull; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.client.RestTemplate; import javax.inject.Inject; import javax.net.ssl.SSLContext; import javax.persistence.EntityManager; import java.util.LinkedList; /** * @author try ma ik jo rr a zib * @version $Id$ * <p/> * User: mjorra, Date: 04.11.2008, Time: 17:45:47 */ public class InterSliceTransferTaskAction extends TaskFlowAction<InterSliceTransferOrder> { private GridConfig config; private HttpMessageConverter messageConverter; private SetupSSL setupSSL; private RestTemplate restTemplate; private SliceClient sliceClient; private SubspaceClient subspaceClient; public InterSliceTransferTaskAction() { super( InterSliceTransferMeta.INTER_SLICE_TRANSFER_KEY ); } public InterSliceTransferTaskAction(@NotNull EntityManager em, @NotNull Dao dao, @NotNull Taskling model) { super(InterSliceTransferMeta.INTER_SLICE_TRANSFER_KEY, em, dao, model); } @Override public Class<InterSliceTransferOrder> getOrderBeanClass() { return InterSliceTransferOrder.class; } @Override protected void onCreated( @NotNull final String wid, @NotNull final TaskState state, final boolean isRestartedTask, final boolean altTaskState ) throws Exception { final Session session = getDao().beginSession(); try { final Task task = getTask( session ); task.setPayload( new InterSliceTransferResult() ); session.success(); } finally { session.finish(); } super.onCreated( wid, state, isRestartedTask, altTaskState ); // overriden method implementation } // TODO: make this method resumable @Override protected void onInProgress(@NotNull String wid, @NotNull TaskState state, boolean isRestartedTask, boolean altTaskState) throws Exception { ensureOrder(); InterSliceTransferQuoteCalculator.prepareSourceUrl( getOrder(), sliceClient ); prepareDestination( ); Session session = getDao().beginSession(); final String subTaskId = getUUIDGen().nextUUID(); try { final Task task = getTask(session); final Task st = task.createSubTask(); st.setId(subTaskId); st.setPayload( null ); st.setTerminationTime( task.getTerminationTime() ); session.success(); } finally { session.finish(); } session = getDao().beginSession(); final FileTransferTaskAction fta; try { final Task task = getTask(session); final Task st = session.findTask( subTaskId ); fta = new FileTransferTaskAction( getEmf().createEntityManager(), getDao(), st.getTaskling() ); getInjector().injectMembers( fta ); fta.setCredentialProvider( getCredentialProvider() ); fta.setEmf( getEmf( ) ); session.success(); } finally { session.finish(); } fta.call( ); session = getDao().beginSession(); try { final Task task = getTask(session); final Task st = session.findTask(subTaskId); if( st.getTaskState().equals( TaskState.FINISHED ) ){ //noinspection ConstantConditions - ( ( InterSliceTransferResult) task.getPayload() ).populate( - ( FileTransferResult ) st.getPayload() ); + final InterSliceTransferResult payload = + ( InterSliceTransferResult ) task.getPayload(); + payload.populate( ( FileTransferResult ) st.getPayload() ); + task.setPayload( payload ); task.setTaskState(TaskState.FINISHED); if (altTaskState) task.setAltTaskState(null); } else throw (RuntimeException) st.getPayload(); session.success(); } finally { session.finish(); } } private void prepareDestination() { final DelegatingOrder<InterSliceTransferOrder> order = getOrder(); final InterSliceTransferOrder orderBean = order.getOrderBean(); if( orderBean.getDestinationURI() != null ) return; Specifier<Void> sliceSpecifier; final Specifier<Void> specifier = orderBean.getDestinationSpecifier(); if( specifier.getUriMap().containsKey( UriFactory.SLICE ) ) { // we got a slice specifier sliceSpecifier = specifier; } else { // must be a slice kind specifier // lets create a new slice ResponseEntity<Specifier<Void>> sliceSpecifierResponse = subspaceClient.createSlice( specifier, order.getDNFromContext() ); if( HttpStatus.CREATED.equals( sliceSpecifierResponse.getStatusCode() ) ) sliceSpecifier = sliceSpecifierResponse.getBody(); else throw new IllegalStateException( "Can't create slice in: " + specifier.getUrl() ); } // fetch grid-ftp uri orderBean.setDestinationURI( getGsiFtpUrl( order, sliceSpecifier ) ); // update task in data-base Session session = getDao().beginSession(); try { Task task = getTask( session ); task.setOrder(order); //noinspection ConstantConditions final InterSliceTransferResult payload = (InterSliceTransferResult) task.getPayload(); payload.setSliceSpecifier( sliceSpecifier ); task.setPayload( payload ); session.success(); } finally { session.finish(); } } private String getGsiFtpUrl( final DelegatingOrder<InterSliceTransferOrder> order, final Specifier<Void> specifier ) { final ResponseEntity<String> responseEntity = sliceClient.getGridFtpUrl( specifier, order.getDNFromContext() ); if( HttpStatus.OK.equals( responseEntity.getStatusCode() ) ) return responseEntity.getBody(); else throw new IllegalStateException( "Can't fetch gridFTP URL for slice: " + specifier.getUrl() ); } public SliceClient getSliceClient() { return sliceClient; } public void prepareSliceClient( ) { if( null != sliceClient ) return; try { sliceClient = new SliceClient( config.getBaseUrl() ); } catch( Exception e ) { logger.error( "Could not get service URL. Please contact system administrator.", e ); } sliceClient.setRestTemplate( restTemplate ); } public SubspaceClient getSubspaceClient() { return subspaceClient; } public void prepareSubspaceClient( ) { if( null != subspaceClient ) return; try { subspaceClient = new SubspaceClient( config.getBaseUrl() ); } catch( Exception e ) { logger.error( "Could not get service URL. Please contact system administrator.", e ); } subspaceClient.setRestTemplate( restTemplate ); } @SuppressWarnings("SpringJavaAutowiringInspection") @Inject public void setConfig( GridConfig config ) { this.config = config; } @SuppressWarnings("SpringJavaAutowiringInspection") @Inject public void setMessageConverter( HttpMessageConverter messageConverter ) { this.messageConverter = messageConverter; } @SuppressWarnings("SpringJavaAutowiringInspection") @Inject public void setSetupSSL( SetupSSL setupSSL ) { this.setupSSL = setupSSL; } public void prepareRestTemplate( String keyPassword ) { SSLContext sslContext = null; try { sslContext = setupSSL.setupSSLContext( keyPassword ); } catch (Exception e) { throw new IllegalStateException( "Could not setup SSL context.", e ); } CustomSSLContextRequestFactory requestFactory = new CustomSSLContextRequestFactory( sslContext ); restTemplate = new RestTemplate( requestFactory ); restTemplate.setMessageConverters( new LinkedList< HttpMessageConverter<?> >(){{ add( messageConverter ); }} ); } }
true
true
protected void onInProgress(@NotNull String wid, @NotNull TaskState state, boolean isRestartedTask, boolean altTaskState) throws Exception { ensureOrder(); InterSliceTransferQuoteCalculator.prepareSourceUrl( getOrder(), sliceClient ); prepareDestination( ); Session session = getDao().beginSession(); final String subTaskId = getUUIDGen().nextUUID(); try { final Task task = getTask(session); final Task st = task.createSubTask(); st.setId(subTaskId); st.setPayload( null ); st.setTerminationTime( task.getTerminationTime() ); session.success(); } finally { session.finish(); } session = getDao().beginSession(); final FileTransferTaskAction fta; try { final Task task = getTask(session); final Task st = session.findTask( subTaskId ); fta = new FileTransferTaskAction( getEmf().createEntityManager(), getDao(), st.getTaskling() ); getInjector().injectMembers( fta ); fta.setCredentialProvider( getCredentialProvider() ); fta.setEmf( getEmf( ) ); session.success(); } finally { session.finish(); } fta.call( ); session = getDao().beginSession(); try { final Task task = getTask(session); final Task st = session.findTask(subTaskId); if( st.getTaskState().equals( TaskState.FINISHED ) ){ //noinspection ConstantConditions ( ( InterSliceTransferResult) task.getPayload() ).populate( ( FileTransferResult ) st.getPayload() ); task.setTaskState(TaskState.FINISHED); if (altTaskState) task.setAltTaskState(null); } else throw (RuntimeException) st.getPayload(); session.success(); } finally { session.finish(); } }
protected void onInProgress(@NotNull String wid, @NotNull TaskState state, boolean isRestartedTask, boolean altTaskState) throws Exception { ensureOrder(); InterSliceTransferQuoteCalculator.prepareSourceUrl( getOrder(), sliceClient ); prepareDestination( ); Session session = getDao().beginSession(); final String subTaskId = getUUIDGen().nextUUID(); try { final Task task = getTask(session); final Task st = task.createSubTask(); st.setId(subTaskId); st.setPayload( null ); st.setTerminationTime( task.getTerminationTime() ); session.success(); } finally { session.finish(); } session = getDao().beginSession(); final FileTransferTaskAction fta; try { final Task task = getTask(session); final Task st = session.findTask( subTaskId ); fta = new FileTransferTaskAction( getEmf().createEntityManager(), getDao(), st.getTaskling() ); getInjector().injectMembers( fta ); fta.setCredentialProvider( getCredentialProvider() ); fta.setEmf( getEmf( ) ); session.success(); } finally { session.finish(); } fta.call( ); session = getDao().beginSession(); try { final Task task = getTask(session); final Task st = session.findTask(subTaskId); if( st.getTaskState().equals( TaskState.FINISHED ) ){ //noinspection ConstantConditions final InterSliceTransferResult payload = ( InterSliceTransferResult ) task.getPayload(); payload.populate( ( FileTransferResult ) st.getPayload() ); task.setPayload( payload ); task.setTaskState(TaskState.FINISHED); if (altTaskState) task.setAltTaskState(null); } else throw (RuntimeException) st.getPayload(); session.success(); } finally { session.finish(); } }
diff --git a/src/com/redhat/ceylon/compiler/loader/AbstractModelLoader.java b/src/com/redhat/ceylon/compiler/loader/AbstractModelLoader.java index e241a9559..7e189d7ff 100644 --- a/src/com/redhat/ceylon/compiler/loader/AbstractModelLoader.java +++ b/src/com/redhat/ceylon/compiler/loader/AbstractModelLoader.java @@ -1,3579 +1,3581 @@ /* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License version 2. * * This particular file is subject to the "Classpath" exception as provided in the * LICENSE file that accompanied this code. * * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License, * along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package com.redhat.ceylon.compiler.loader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.lang.model.type.TypeKind; import com.redhat.ceylon.cmr.api.ArtifactResult; import com.redhat.ceylon.cmr.api.JDKUtils; import com.redhat.ceylon.common.Versions; import com.redhat.ceylon.compiler.java.codegen.AbstractTransformer; import com.redhat.ceylon.compiler.java.codegen.AnnotationArgument; import com.redhat.ceylon.compiler.java.codegen.AnnotationConstructorParameter; import com.redhat.ceylon.compiler.java.codegen.AnnotationFieldName; import com.redhat.ceylon.compiler.java.codegen.AnnotationInvocation; import com.redhat.ceylon.compiler.java.codegen.AnnotationTerm; import com.redhat.ceylon.compiler.java.codegen.BooleanLiteralAnnotationTerm; import com.redhat.ceylon.compiler.java.codegen.CharacterLiteralAnnotationTerm; import com.redhat.ceylon.compiler.java.codegen.CollectionLiteralAnnotationTerm; import com.redhat.ceylon.compiler.java.codegen.Decl; import com.redhat.ceylon.compiler.java.codegen.DeclarationLiteralAnnotationTerm; import com.redhat.ceylon.compiler.java.codegen.FloatLiteralAnnotationTerm; import com.redhat.ceylon.compiler.java.codegen.IntegerLiteralAnnotationTerm; import com.redhat.ceylon.compiler.java.codegen.InvocationAnnotationTerm; import com.redhat.ceylon.compiler.java.codegen.LiteralAnnotationTerm; import com.redhat.ceylon.compiler.java.codegen.Naming; import com.redhat.ceylon.compiler.java.codegen.ObjectLiteralAnnotationTerm; import com.redhat.ceylon.compiler.java.codegen.ParameterAnnotationTerm; import com.redhat.ceylon.compiler.java.codegen.StringLiteralAnnotationTerm; import com.redhat.ceylon.compiler.java.util.Timer; import com.redhat.ceylon.compiler.java.util.Util; import com.redhat.ceylon.compiler.loader.mirror.AccessibleMirror; import com.redhat.ceylon.compiler.loader.mirror.AnnotatedMirror; import com.redhat.ceylon.compiler.loader.mirror.AnnotationMirror; import com.redhat.ceylon.compiler.loader.mirror.ClassMirror; import com.redhat.ceylon.compiler.loader.mirror.FieldMirror; import com.redhat.ceylon.compiler.loader.mirror.MethodMirror; import com.redhat.ceylon.compiler.loader.mirror.PackageMirror; import com.redhat.ceylon.compiler.loader.mirror.TypeMirror; import com.redhat.ceylon.compiler.loader.mirror.TypeParameterMirror; import com.redhat.ceylon.compiler.loader.mirror.VariableMirror; import com.redhat.ceylon.compiler.loader.model.FieldValue; import com.redhat.ceylon.compiler.loader.model.JavaBeanValue; import com.redhat.ceylon.compiler.loader.model.JavaMethod; import com.redhat.ceylon.compiler.loader.model.LazyClass; import com.redhat.ceylon.compiler.loader.model.LazyClassAlias; import com.redhat.ceylon.compiler.loader.model.LazyContainer; import com.redhat.ceylon.compiler.loader.model.LazyElement; import com.redhat.ceylon.compiler.loader.model.LazyInterface; import com.redhat.ceylon.compiler.loader.model.LazyInterfaceAlias; import com.redhat.ceylon.compiler.loader.model.LazyMethod; import com.redhat.ceylon.compiler.loader.model.LazyModule; import com.redhat.ceylon.compiler.loader.model.LazyPackage; import com.redhat.ceylon.compiler.loader.model.LazyTypeAlias; import com.redhat.ceylon.compiler.loader.model.LazyValue; import com.redhat.ceylon.compiler.typechecker.analyzer.DeclarationVisitor; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleManager; import com.redhat.ceylon.compiler.typechecker.model.Annotation; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Element; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.Interface; import com.redhat.ceylon.compiler.typechecker.model.IntersectionType; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.ModuleImport; import com.redhat.ceylon.compiler.typechecker.model.Modules; import com.redhat.ceylon.compiler.typechecker.model.NothingType; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ParameterList; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.TypeAlias; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.model.UnionType; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.model.UnknownType; import com.redhat.ceylon.compiler.typechecker.model.Value; /** * Abstract class of a model loader that can load a model from a compiled Java representation, * while being agnostic of the reflection API used to load the compiled Java representation. * * @author Stéphane Épardaud <[email protected]> */ public abstract class AbstractModelLoader implements ModelCompleter, ModelLoader { public static final String JAVA_BASE_MODULE_NAME = "java.base"; public static final String CEYLON_LANGUAGE = "ceylon.language"; public static final String CEYLON_LANGUAGE_MODEL = "ceylon.language.meta.model"; public static final String CEYLON_LANGUAGE_MODEL_DECLARATION = "ceylon.language.meta.declaration"; private static final String TIMER_MODEL_LOADER_CATEGORY = "model loader"; public static final String JDK_MODULE_VERSION = "7"; public static final String CEYLON_CEYLON_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Ceylon"; private static final String CEYLON_MODULE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Module"; private static final String CEYLON_PACKAGE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Package"; private static final String CEYLON_IGNORE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Ignore"; private static final String CEYLON_CLASS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Class"; public static final String CEYLON_NAME_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Name"; private static final String CEYLON_SEQUENCED_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Sequenced"; private static final String CEYLON_FUNCTIONAL_PARAMETER_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.FunctionalParameter"; private static final String CEYLON_DEFAULTED_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Defaulted"; private static final String CEYLON_SATISFIED_TYPES_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes"; private static final String CEYLON_CASE_TYPES_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.CaseTypes"; private static final String CEYLON_TYPE_PARAMETERS = "com.redhat.ceylon.compiler.java.metadata.TypeParameters"; private static final String CEYLON_TYPE_INFO_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.TypeInfo"; public static final String CEYLON_ATTRIBUTE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Attribute"; public static final String CEYLON_OBJECT_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Object"; public static final String CEYLON_METHOD_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Method"; public static final String CEYLON_CONTAINER_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Container"; public static final String CEYLON_LOCAL_CONTAINER_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.LocalContainer"; private static final String CEYLON_MEMBERS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Members"; private static final String CEYLON_ANNOTATIONS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Annotations"; public static final String CEYLON_VALUETYPE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.ValueType"; public static final String CEYLON_ALIAS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Alias"; public static final String CEYLON_TYPE_ALIAS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.TypeAlias"; private static final String CEYLON_ANNOTATION_INSTANTIATION_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.AnnotationInstantiation"; private static final String CEYLON_ANNOTATION_INSTANTIATION_ARGUMENTS_MEMBER = "arguments"; private static final String CEYLON_ANNOTATION_INSTANTIATION_ANNOTATION_MEMBER = "primary"; private static final String CEYLON_ANNOTATION_INSTANTIATION_TREE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.AnnotationInstantiationTree"; private static final String CEYLON_STRING_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.StringValue"; private static final String CEYLON_STRING_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.StringExprs"; private static final String CEYLON_BOOLEAN_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.BooleanValue"; private static final String CEYLON_BOOLEAN_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.BooleanExprs"; private static final String CEYLON_INTEGER_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.IntegerValue"; private static final String CEYLON_INTEGER_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.IntegerExprs"; private static final String CEYLON_CHARACTER_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.CharacterValue"; private static final String CEYLON_CHARACTER_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.CharacterExprs"; private static final String CEYLON_FLOAT_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.FloatValue"; private static final String CEYLON_FLOAT_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.FloatExprs"; private static final String CEYLON_OBJECT_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.ObjectValue"; private static final String CEYLON_OBJECT_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.ObjectExprs"; private static final String CEYLON_DECLARATION_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.DeclarationValue"; private static final String CEYLON_DECLARATION_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.DeclarationExprs"; private static final String CEYLON_PARAMETER_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.ParameterValue"; private static final String CEYLON_TRANSIENT_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Transient"; private static final String JAVA_DEPRECATED_ANNOTATION = "java.lang.Deprecated"; private static final String CEYLON_LANGUAGE_ABSTRACT_ANNOTATION = "ceylon.language.AbstractAnnotation$annotation"; private static final String CEYLON_LANGUAGE_ACTUAL_ANNOTATION = "ceylon.language.ActualAnnotation$annotation"; private static final String CEYLON_LANGUAGE_ANNOTATION_ANNOTATION = "ceylon.language.AnnotationAnnotation$annotation"; private static final String CEYLON_LANGUAGE_DEFAULT_ANNOTATION = "ceylon.language.DefaultAnnotation$annotation"; private static final String CEYLON_LANGUAGE_FORMAL_ANNOTATION = "ceylon.language.FormalAnnotation$annotation"; private static final String CEYLON_LANGUAGE_LATE_ANNOTATION = "ceylon.language.LateAnnotation$annotation"; private static final String CEYLON_LANGUAGE_SHARED_ANNOTATION = "ceylon.language.SharedAnnotation$annotation"; private static final TypeMirror OBJECT_TYPE = simpleCeylonObjectType("java.lang.Object"); private static final TypeMirror CEYLON_OBJECT_TYPE = simpleCeylonObjectType("ceylon.language.Object"); private static final TypeMirror CEYLON_BASIC_TYPE = simpleCeylonObjectType("ceylon.language.Basic"); private static final TypeMirror CEYLON_EXCEPTION_TYPE = simpleCeylonObjectType("ceylon.language.Exception"); private static final TypeMirror CEYLON_REIFIED_TYPE_TYPE = simpleCeylonObjectType("com.redhat.ceylon.compiler.java.runtime.model.ReifiedType"); private static final TypeMirror CEYLON_TYPE_DESCRIPTOR_TYPE = simpleCeylonObjectType("com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor"); private static final TypeMirror STRING_TYPE = simpleJDKObjectType("java.lang.String"); private static final TypeMirror CEYLON_STRING_TYPE = simpleCeylonObjectType("ceylon.language.String"); private static final TypeMirror PRIM_BOOLEAN_TYPE = simpleJDKObjectType("boolean"); private static final TypeMirror BOOLEAN_TYPE = simpleJDKObjectType("java.lang.Boolean"); private static final TypeMirror CEYLON_BOOLEAN_TYPE = simpleCeylonObjectType("ceylon.language.Boolean"); private static final TypeMirror PRIM_BYTE_TYPE = simpleJDKObjectType("byte"); private static final TypeMirror BYTE_TYPE = simpleJDKObjectType("java.lang.Byte"); private static final TypeMirror PRIM_SHORT_TYPE = simpleJDKObjectType("short"); private static final TypeMirror SHORT_TYPE = simpleJDKObjectType("java.lang.Short"); private static final TypeMirror PRIM_INT_TYPE = simpleJDKObjectType("int"); private static final TypeMirror INTEGER_TYPE = simpleJDKObjectType("java.lang.Integer"); private static final TypeMirror PRIM_LONG_TYPE = simpleJDKObjectType("long"); private static final TypeMirror LONG_TYPE = simpleJDKObjectType("java.lang.Long"); private static final TypeMirror CEYLON_INTEGER_TYPE = simpleCeylonObjectType("ceylon.language.Integer"); private static final TypeMirror PRIM_FLOAT_TYPE = simpleJDKObjectType("float"); private static final TypeMirror FLOAT_TYPE = simpleJDKObjectType("java.lang.Float"); private static final TypeMirror PRIM_DOUBLE_TYPE = simpleJDKObjectType("double"); private static final TypeMirror DOUBLE_TYPE = simpleJDKObjectType("java.lang.Double"); private static final TypeMirror CEYLON_FLOAT_TYPE = simpleCeylonObjectType("ceylon.language.Float"); private static final TypeMirror PRIM_CHAR_TYPE = simpleJDKObjectType("char"); private static final TypeMirror CHARACTER_TYPE = simpleJDKObjectType("java.lang.Character"); private static final TypeMirror CEYLON_CHARACTER_TYPE = simpleCeylonObjectType("ceylon.language.Character"); private static final TypeMirror CEYLON_ARRAY_TYPE = simpleCeylonObjectType("ceylon.language.Array"); // this one has no "_" postfix because that's how we look it up protected static final String JAVA_LANG_ARRAYS = "java.lang.arrays"; protected static final String JAVA_LANG_BYTE_ARRAY = "java.lang.ByteArray"; protected static final String JAVA_LANG_SHORT_ARRAY = "java.lang.ShortArray"; protected static final String JAVA_LANG_INT_ARRAY = "java.lang.IntArray"; protected static final String JAVA_LANG_LONG_ARRAY = "java.lang.LongArray"; protected static final String JAVA_LANG_FLOAT_ARRAY = "java.lang.FloatArray"; protected static final String JAVA_LANG_DOUBLE_ARRAY = "java.lang.DoubleArray"; protected static final String JAVA_LANG_CHAR_ARRAY = "java.lang.CharArray"; protected static final String JAVA_LANG_BOOLEAN_ARRAY = "java.lang.BooleanArray"; protected static final String JAVA_LANG_OBJECT_ARRAY = "java.lang.ObjectArray"; // this one has the "_" postfix because that's what we translate it to private static final String CEYLON_ARRAYS = "com.redhat.ceylon.compiler.java.language.arrays_"; private static final String CEYLON_BYTE_ARRAY = "com.redhat.ceylon.compiler.java.language.ByteArray"; private static final String CEYLON_SHORT_ARRAY = "com.redhat.ceylon.compiler.java.language.ShortArray"; private static final String CEYLON_INT_ARRAY = "com.redhat.ceylon.compiler.java.language.IntArray"; private static final String CEYLON_LONG_ARRAY = "com.redhat.ceylon.compiler.java.language.LongArray"; private static final String CEYLON_FLOAT_ARRAY = "com.redhat.ceylon.compiler.java.language.FloatArray"; private static final String CEYLON_DOUBLE_ARRAY = "com.redhat.ceylon.compiler.java.language.DoubleArray"; private static final String CEYLON_CHAR_ARRAY = "com.redhat.ceylon.compiler.java.language.CharArray"; private static final String CEYLON_BOOLEAN_ARRAY = "com.redhat.ceylon.compiler.java.language.BooleanArray"; private static final String CEYLON_OBJECT_ARRAY = "com.redhat.ceylon.compiler.java.language.ObjectArray"; private static final TypeMirror JAVA_BYTE_ARRAY_TYPE = simpleJDKObjectType("java.lang.ByteArray"); private static final TypeMirror JAVA_SHORT_ARRAY_TYPE = simpleJDKObjectType("java.lang.ShortArray"); private static final TypeMirror JAVA_INT_ARRAY_TYPE = simpleJDKObjectType("java.lang.IntArray"); private static final TypeMirror JAVA_LONG_ARRAY_TYPE = simpleJDKObjectType("java.lang.LongArray"); private static final TypeMirror JAVA_FLOAT_ARRAY_TYPE = simpleJDKObjectType("java.lang.FloatArray"); private static final TypeMirror JAVA_DOUBLE_ARRAY_TYPE = simpleJDKObjectType("java.lang.DoubleArray"); private static final TypeMirror JAVA_CHAR_ARRAY_TYPE = simpleJDKObjectType("java.lang.CharArray"); private static final TypeMirror JAVA_BOOLEAN_ARRAY_TYPE = simpleJDKObjectType("java.lang.BooleanArray"); private static final TypeMirror JAVA_OBJECT_ARRAY_TYPE = simpleJDKObjectType("java.lang.ObjectArray"); private static TypeMirror simpleJDKObjectType(String name) { return new SimpleReflType(name, SimpleReflType.Module.JDK, TypeKind.DECLARED); } private static TypeMirror simpleCeylonObjectType(String name) { return new SimpleReflType(name, SimpleReflType.Module.CEYLON, TypeKind.DECLARED); } protected Map<String, Declaration> declarationsByName = new HashMap<String, Declaration>(); protected Map<Package, Unit> unitsByPackage = new HashMap<Package, Unit>(); protected TypeParser typeParser; protected Unit typeFactory; protected final Set<String> loadedPackages = new HashSet<String>(); protected final Map<String,LazyPackage> packagesByName = new HashMap<String,LazyPackage>(); protected boolean packageDescriptorsNeedLoading = false; protected boolean isBootstrap; protected ModuleManager moduleManager; protected Modules modules; protected Map<String, ClassMirror> classMirrorCache = new HashMap<String, ClassMirror>(); protected boolean binaryCompatibilityErrorRaised = false; protected Timer timer; private Map<String,LazyPackage> modulelessPackages = new HashMap<String,LazyPackage>(); /** * Loads a given package, if required. This is mostly useful for the javac reflection impl. * * @param the module to load the package from * @param packageName the package name to load * @param loadDeclarations true to load all the declarations in this package. * @return */ public abstract boolean loadPackage(Module module, String packageName, boolean loadDeclarations); /** * Looks up a ClassMirror by name. Uses cached results, and caches the result of calling lookupNewClassMirror * on cache misses. * * @param module the module in which we should find the class * @param name the name of the Class to load * @return a ClassMirror for the specified class, or null if not found. */ public synchronized final ClassMirror lookupClassMirror(Module module, String name){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); try{ // Java array classes are not where we expect them if (JAVA_LANG_OBJECT_ARRAY.equals(name) || JAVA_LANG_BOOLEAN_ARRAY.equals(name) || JAVA_LANG_BYTE_ARRAY.equals(name) || JAVA_LANG_SHORT_ARRAY.equals(name) || JAVA_LANG_INT_ARRAY.equals(name) || JAVA_LANG_LONG_ARRAY.equals(name) || JAVA_LANG_FLOAT_ARRAY.equals(name) || JAVA_LANG_DOUBLE_ARRAY.equals(name) || JAVA_LANG_CHAR_ARRAY.equals(name) || JAVA_LANG_ARRAYS.equals(name)) { // turn them into their real class location (get rid of the "java.lang" prefix) name = "com.redhat.ceylon.compiler.java.language" + name.substring(9); module = getLanguageModule(); } String cacheKey = cacheKeyByModule(module, name); // we use containsKey to be able to cache null results if(classMirrorCache.containsKey(cacheKey)) return classMirrorCache.get(cacheKey); ClassMirror mirror = lookupNewClassMirror(module, name); // we even cache null results classMirrorCache.put(cacheKey, mirror); return mirror; }finally{ timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } protected String cacheKeyByModule(Module module, String name) { // '/' is allowed in module version but not in module or class name, so we're good if(module.isDefault()) return module.getNameAsString() + '/' + name; // no version return module.getNameAsString() + '/' + module.getVersion() + '/' + name; } protected boolean lastPartHasLowerInitial(String name) { int index = name.lastIndexOf('.'); if (index != -1){ name = name.substring(index+1); } if(!name.isEmpty()){ char c = name.charAt(0); return Util.isLowerCase(c); } return false; } /** * Looks up a ClassMirror by name. Called by lookupClassMirror on cache misses. * * @param module the module in which we should find the given class * @param name the name of the Class to load * @return a ClassMirror for the specified class, or null if not found. */ protected abstract ClassMirror lookupNewClassMirror(Module module, String name); /** * Adds the given module to the set of modules from which we can load classes. * * @param module the module * @param artifact the module's artifact, if any. Can be null. */ public abstract void addModuleToClassPath(Module module, ArtifactResult artifact); /** * Returns true if the given method is overriding an inherited method (from super class or interfaces). */ protected abstract boolean isOverridingMethod(MethodMirror methodMirror); /** * Logs a warning. */ protected abstract void logWarning(String message); /** * Logs a debug message. */ protected abstract void logVerbose(String message); /** * Logs an error */ protected abstract void logError(String message); public void loadStandardModules(){ // set up the type factory Module languageModule = findOrCreateModule(CEYLON_LANGUAGE, null); addModuleToClassPath(languageModule, null); Package languagePackage = findOrCreatePackage(languageModule, CEYLON_LANGUAGE); typeFactory.setPackage(languagePackage); // make sure the jdk modules are loaded for(String jdkModule : JDKUtils.getJDKModuleNames()) findOrCreateModule(jdkModule, JDK_MODULE_VERSION); for(String jdkOracleModule : JDKUtils.getOracleJDKModuleNames()) findOrCreateModule(jdkOracleModule, JDK_MODULE_VERSION); Module jdkModule = findOrCreateModule(JAVA_BASE_MODULE_NAME, JDK_MODULE_VERSION); /* * We start by loading java.lang and ceylon.language because we will need them no matter what. */ loadPackage(jdkModule, "java.lang", false); loadPackage(languageModule, "com.redhat.ceylon.compiler.java.metadata", false); /* * We do not load the ceylon.language module from class files if we're bootstrapping it */ if(!isBootstrap){ loadPackage(languageModule, CEYLON_LANGUAGE, true); loadPackage(languageModule, CEYLON_LANGUAGE_MODEL, true); loadPackage(languageModule, CEYLON_LANGUAGE_MODEL_DECLARATION, true); } } /** * This is meant to be called if your subclass doesn't call loadStandardModules for whatever reason */ public void setupWithNoStandardModules() { Module languageModule = modules.getLanguageModule(); if(languageModule == null) throw new RuntimeException("Assertion failed: language module is null"); Package languagePackage = languageModule.getPackage(CEYLON_LANGUAGE); if(languagePackage == null) throw new RuntimeException("Assertion failed: language package is null"); typeFactory.setPackage(languagePackage); } enum ClassType { ATTRIBUTE, METHOD, OBJECT, CLASS, INTERFACE; } private ClassMirror loadClass(Module module, String pkgName, String className) { ClassMirror moduleClass = null; try{ loadPackage(module, pkgName, false); moduleClass = lookupClassMirror(module, className); }catch(Exception x){ logVerbose("[Failed to complete class "+className+"]"); } return moduleClass; } private Declaration convertNonPrimitiveTypeToDeclaration(TypeMirror type, Scope scope, DeclarationType declarationType) { switch(type.getKind()){ case VOID: return typeFactory.getAnythingDeclaration(); case ARRAY: return ((Class)convertToDeclaration(getLanguageModule(), JAVA_LANG_OBJECT_ARRAY, DeclarationType.TYPE)); case DECLARED: return convertDeclaredTypeToDeclaration(type, declarationType); case TYPEVAR: return safeLookupTypeParameter(scope, type.getQualifiedName()); case WILDCARD: return typeFactory.getNothingDeclaration(); // those can't happen case BOOLEAN: case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT: case DOUBLE: // all the autoboxing should already have been done throw new RuntimeException("Expected non-primitive type: "+type); default: throw new RuntimeException("Failed to handle type "+type); } } private Declaration convertDeclaredTypeToDeclaration(TypeMirror type, DeclarationType declarationType) { // SimpleReflType does not do declared class so we make an exception for it String typeName = type.getQualifiedName(); if(type instanceof SimpleReflType){ Module module = null; switch(((SimpleReflType) type).getModule()){ case CEYLON: module = getLanguageModule(); break; case JDK : module = getJDKBaseModule(); break; } return convertToDeclaration(module, typeName, declarationType); } ClassMirror classMirror = type.getDeclaredClass(); Module module = findModuleForClassMirror(classMirror); return convertToDeclaration(module, typeName, declarationType); } protected Declaration convertToDeclaration(ClassMirror classMirror, DeclarationType declarationType) { // avoid ignored classes if(classMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) return null; // avoid module and package descriptors too if(classMirror.getAnnotation(CEYLON_MODULE_ANNOTATION) != null || classMirror.getAnnotation(CEYLON_PACKAGE_ANNOTATION) != null) return null; List<Declaration> decls = new ArrayList<Declaration>(); Module module = findModuleForClassMirror(classMirror); boolean[] alreadyExists = new boolean[1]; Declaration decl = getOrCreateDeclaration(module, classMirror, declarationType, decls, alreadyExists); if (alreadyExists[0]) { return decl; } // find its package String pkgName = getPackageNameForQualifiedClassName(classMirror); LazyPackage pkg = findOrCreatePackage(module, pkgName); // find/make its Unit Unit unit = getCompiledUnit(pkg, classMirror); // set all the containers for(Declaration d : decls){ // add it to its Unit d.setUnit(unit); unit.addDeclaration(d); setContainer(classMirror, d, pkg); } return decl; } protected String getPackageNameForQualifiedClassName(ClassMirror classMirror) { String qualifiedName = classMirror.getQualifiedName(); // Java array classes we pretend come from java.lang if(qualifiedName.equals(CEYLON_OBJECT_ARRAY) || qualifiedName.equals(CEYLON_BOOLEAN_ARRAY) || qualifiedName.equals(CEYLON_BYTE_ARRAY) || qualifiedName.equals(CEYLON_SHORT_ARRAY) || qualifiedName.equals(CEYLON_INT_ARRAY) || qualifiedName.equals(CEYLON_LONG_ARRAY) || qualifiedName.equals(CEYLON_FLOAT_ARRAY) || qualifiedName.equals(CEYLON_DOUBLE_ARRAY) || qualifiedName.equals(CEYLON_CHAR_ARRAY) || qualifiedName.equals(CEYLON_ARRAYS) ) return "java.lang"; else return classMirror.getPackage().getQualifiedName(); } private void setContainer(ClassMirror classMirror, Declaration d, LazyPackage pkg) { // add it to its package if it's not an inner class if(!classMirror.isInnerClass() && !classMirror.isLocalClass()){ d.setContainer(pkg); pkg.addCompiledMember(d); }else if(classMirror.isLocalClass()){ // set its container to the package for now, but don't add it to the package as a member because it's not d.setContainer(pkg); ((LazyElement)d).setLocal(true); }else if(d instanceof ClassOrInterface || d instanceof TypeAlias){ // do overloads later, since their container is their abstract superclass's container and // we have to set that one first if(d instanceof Class == false || !((Class)d).isOverloaded()){ ClassOrInterface container = getContainer(pkg.getModule(), classMirror); d.setContainer(container); // let's not trigger lazy-loading ((LazyContainer)container).addMember(d); // now we can do overloads if(d instanceof Class && ((Class)d).getOverloads() != null){ for(Declaration overload : ((Class)d).getOverloads()){ overload.setContainer(container); // let's not trigger lazy-loading ((LazyContainer)container).addMember(d); } } } } } private ClassOrInterface getContainer(Module module, ClassMirror classMirror) { AnnotationMirror containerAnnotation = classMirror.getAnnotation(CEYLON_CONTAINER_ANNOTATION); if(containerAnnotation != null){ TypeMirror javaClassMirror = (TypeMirror)containerAnnotation.getValue("klass"); String javaClassName = javaClassMirror.getQualifiedName(); ClassOrInterface containerDecl = (ClassOrInterface) convertToDeclaration(module, javaClassName, DeclarationType.TYPE); if(containerDecl == null) throw new ModelResolutionException("Failed to load outer type " + javaClassName + " for inner type " + classMirror.getQualifiedName().toString()); return containerDecl; }else{ return (ClassOrInterface) convertToDeclaration(classMirror.getEnclosingClass(), DeclarationType.TYPE); } } protected Declaration getOrCreateDeclaration(Module module, ClassMirror classMirror, DeclarationType declarationType, List<Declaration> decls, boolean[] alreadyExists) { alreadyExists[0] = false; Declaration decl = null; String className = classMirror.getQualifiedName(); ClassType type; String prefix; if(classMirror.isCeylonToplevelAttribute()){ type = ClassType.ATTRIBUTE; prefix = "V"; }else if(classMirror.isCeylonToplevelMethod()){ type = ClassType.METHOD; prefix = "V"; }else if(classMirror.isCeylonToplevelObject()){ type = ClassType.OBJECT; // depends on which one we want prefix = declarationType == DeclarationType.TYPE ? "C" : "V"; }else if(classMirror.isInterface()){ type = ClassType.INTERFACE; prefix = "C"; }else{ type = ClassType.CLASS; prefix = "C"; } String key = cacheKeyByModule(module, prefix + className); // see if we already have it if(declarationsByName.containsKey(key)){ alreadyExists[0] = true; return declarationsByName.get(key); } checkBinaryCompatibility(classMirror); boolean isCeylon = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null; // make it switch(type){ case ATTRIBUTE: decl = makeToplevelAttribute(classMirror); setDeclarationVisibility(decl, classMirror, classMirror, true); break; case METHOD: decl = makeToplevelMethod(classMirror); setDeclarationVisibility(decl, classMirror, classMirror, true); break; case OBJECT: // we first make a class Declaration objectClassDecl = makeLazyClass(classMirror, null, null, true); declarationsByName.put(cacheKeyByModule(module, "C"+className), objectClassDecl); decls.add(objectClassDecl); // then we make a value for it Declaration objectDecl = makeToplevelAttribute(classMirror); declarationsByName.put(cacheKeyByModule(module, "V"+className), objectDecl); decls.add(objectDecl); // which one did we want? decl = declarationType == DeclarationType.TYPE ? objectClassDecl : objectDecl; setDeclarationVisibility(objectClassDecl, classMirror, classMirror, true); setDeclarationVisibility(objectDecl, classMirror, classMirror, true); break; case CLASS: if(classMirror.getAnnotation(CEYLON_ALIAS_ANNOTATION) != null){ decl = makeClassAlias(classMirror); setDeclarationVisibility(decl, classMirror, classMirror, true); }else if(classMirror.getAnnotation(CEYLON_TYPE_ALIAS_ANNOTATION) != null){ decl = makeTypeAlias(classMirror); setDeclarationVisibility(decl, classMirror, classMirror, true); }else{ List<MethodMirror> constructors = getClassConstructors(classMirror); if (!constructors.isEmpty()) { if (constructors.size() > 1) { decl = makeOverloadedConstructor(constructors, classMirror, decls, isCeylon); } else { // single constructor MethodMirror constructor = constructors.get(0); // if the class and constructor have different visibility, we pretend there's an overload of one // if it's a ceylon class we don't care that they don't match sometimes, like for inner classes // where the constructor is protected because we want to use an accessor, in this case the class // visibility is to be used if(isCeylon || getJavaVisibility(classMirror) == getJavaVisibility(constructor)){ decl = makeLazyClass(classMirror, null, constructor, false); setDeclarationVisibility(decl, classMirror, classMirror, isCeylon); }else{ decl = makeOverloadedConstructor(constructors, classMirror, decls, isCeylon); } } } else { decl = makeLazyClass(classMirror, null, null, false); setDeclarationVisibility(decl, classMirror, classMirror, isCeylon); } } break; case INTERFACE: if(classMirror.getAnnotation(CEYLON_ALIAS_ANNOTATION) != null){ decl = makeInterfaceAlias(classMirror); }else{ decl = makeLazyInterface(classMirror); } setDeclarationVisibility(decl, classMirror, classMirror, isCeylon); break; } // objects have special handling above if(type != ClassType.OBJECT){ declarationsByName.put(key, decl); decls.add(decl); } return decl; } private Declaration makeOverloadedConstructor(List<MethodMirror> constructors, ClassMirror classMirror, List<Declaration> decls, boolean isCeylon) { // If the class has multiple constructors we make a copy of the class // for each one (each with it's own single constructor) and make them // a subclass of the original Class supercls = makeLazyClass(classMirror, null, null, false); // the abstraction class gets the class modifiers setDeclarationVisibility(supercls, classMirror, classMirror, isCeylon); supercls.setAbstraction(true); List<Declaration> overloads = new ArrayList<Declaration>(constructors.size()); // all filtering is done in getClassConstructors for (MethodMirror constructor : constructors) { LazyClass subdecl = makeLazyClass(classMirror, supercls, constructor, false); // the subclasses class get the constructor modifiers setDeclarationVisibility(subdecl, constructor, classMirror, isCeylon); subdecl.setOverloaded(true); overloads.add(subdecl); decls.add(subdecl); } supercls.setOverloads(overloads); return supercls; } private void setDeclarationVisibility(Declaration decl, AccessibleMirror mirror, ClassMirror classMirror, boolean isCeylon) { if(isCeylon){ decl.setShared(mirror.isPublic()); }else{ decl.setShared(mirror.isPublic() || (mirror.isDefaultAccess() && classMirror.isInnerClass()) || mirror.isProtected()); decl.setPackageVisibility(mirror.isDefaultAccess()); decl.setProtectedVisibility(mirror.isProtected()); } } private enum JavaVisibility { PRIVATE, PACKAGE, PROTECTED, PUBLIC; } private JavaVisibility getJavaVisibility(AccessibleMirror mirror) { if(mirror.isPublic()) return JavaVisibility.PUBLIC; if(mirror.isProtected()) return JavaVisibility.PROTECTED; if(mirror.isDefaultAccess()) return JavaVisibility.PACKAGE; return JavaVisibility.PRIVATE; } private Declaration makeClassAlias(ClassMirror classMirror) { return new LazyClassAlias(classMirror, this); } private Declaration makeTypeAlias(ClassMirror classMirror) { return new LazyTypeAlias(classMirror, this); } private Declaration makeInterfaceAlias(ClassMirror classMirror) { return new LazyInterfaceAlias(classMirror, this); } private void checkBinaryCompatibility(ClassMirror classMirror) { // let's not report it twice if(binaryCompatibilityErrorRaised) return; AnnotationMirror annotation = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION); if(annotation == null) return; // Java class, no check Integer major = (Integer) annotation.getValue("major"); if(major == null) major = 0; Integer minor = (Integer) annotation.getValue("minor"); if(minor == null) minor = 0; if(major != Versions.JVM_BINARY_MAJOR_VERSION || minor != Versions.JVM_BINARY_MINOR_VERSION){ logError("Ceylon class " + classMirror.getQualifiedName() + " was compiled by an incompatible version of the Ceylon compiler" +"\nThe class was compiled using "+major+"."+minor+"." +"\nThis compiler supports "+Versions.JVM_BINARY_MAJOR_VERSION+"."+Versions.JVM_BINARY_MINOR_VERSION+"." +"\nPlease try to recompile your module using a compatible compiler." +"\nBinary compatibility will only be supported after Ceylon 1.0."); binaryCompatibilityErrorRaised = true; } } private List<MethodMirror> getClassConstructors(ClassMirror classMirror) { LinkedList<MethodMirror> constructors = new LinkedList<MethodMirror>(); boolean isFromJDK = isFromJDK(classMirror); for(MethodMirror methodMirror : classMirror.getDirectMethods()){ // We skip members marked with @Ignore if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(!methodMirror.isConstructor()) continue; // FIXME: tmp hack to skip constructors that have type params as we don't handle them yet if(!methodMirror.getTypeParameters().isEmpty()) continue; // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !methodMirror.isPublic()) continue; // if we are expecting Ceylon code, check that we have enough reified type parameters if(classMirror.getAnnotation(AbstractModelLoader.CEYLON_CEYLON_ANNOTATION) != null){ if(!checkReifiedTypeDescriptors(classMirror.getTypeParameters().size(), classMirror, methodMirror, true)) continue; } constructors.add(methodMirror); } return constructors; } private boolean checkReifiedTypeDescriptors(int tpCount, ClassMirror container, MethodMirror methodMirror, boolean isConstructor) { List<VariableMirror> params = methodMirror.getParameters(); int actualTypeDescriptorParameters = 0; for(VariableMirror param : params){ if(param.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null && sameType(CEYLON_TYPE_DESCRIPTOR_TYPE, param.getType())){ actualTypeDescriptorParameters++; }else break; } if(tpCount != actualTypeDescriptorParameters){ if(isConstructor) logError("Constructor for '"+container.getQualifiedName()+"' should take "+tpCount +" reified type arguments (TypeDescriptor) but has '"+actualTypeDescriptorParameters+"': skipping constructor."); else logError("Method '"+container.getQualifiedName()+"."+methodMirror.getName()+"' should take "+tpCount +" reified type arguments (TypeDescriptor) but has '"+actualTypeDescriptorParameters+"': method is invalid."); return false; } return true; } protected Unit getCompiledUnit(LazyPackage pkg, ClassMirror classMirror) { Unit unit = unitsByPackage.get(pkg); if(unit == null){ unit = new Unit(); unit.setPackage(pkg); unitsByPackage.put(pkg, unit); } return unit; } protected LazyValue makeToplevelAttribute(ClassMirror classMirror) { LazyValue value = new LazyValue(classMirror, this); return value; } protected LazyMethod makeToplevelMethod(ClassMirror classMirror) { LazyMethod method = new LazyMethod(classMirror, this); return method; } protected LazyClass makeLazyClass(ClassMirror classMirror, Class superClass, MethodMirror constructor, boolean forTopLevelObject) { LazyClass klass = new LazyClass(classMirror, this, superClass, constructor, forTopLevelObject); klass.setAnonymous(classMirror.getAnnotation(CEYLON_OBJECT_ANNOTATION) != null); klass.setAnnotation(classMirror.getAnnotation(CEYLON_LANGUAGE_ANNOTATION_ANNOTATION) != null); if(klass.isCeylon()) klass.setAbstract(classMirror.getAnnotation(CEYLON_LANGUAGE_ABSTRACT_ANNOTATION) != null // for toplevel classes if the annotation is missing we respect the java abstract modifier // for member classes that would be ambiguous between formal and abstract so we don't and require // the model annotation || (!classMirror.isInnerClass() && !classMirror.isLocalClass() && classMirror.isAbstract())); else klass.setAbstract(classMirror.isAbstract()); klass.setFormal(classMirror.getAnnotation(CEYLON_LANGUAGE_FORMAL_ANNOTATION) != null); klass.setDefault(classMirror.getAnnotation(CEYLON_LANGUAGE_DEFAULT_ANNOTATION) != null); klass.setActual(classMirror.getAnnotation(CEYLON_LANGUAGE_ACTUAL_ANNOTATION) != null); klass.setFinal(classMirror.isFinal()); klass.setStaticallyImportable(!klass.isCeylon() && classMirror.isStatic()); return klass; } protected LazyInterface makeLazyInterface(ClassMirror classMirror) { LazyInterface iface = new LazyInterface(classMirror, this); return iface; } public synchronized Declaration convertToDeclaration(Module module, String typeName, DeclarationType declarationType) { // FIXME: this needs to move to the type parser and report warnings //This should be done where the TypeInfo annotation is parsed //to avoid retarded errors because of a space after a comma typeName = typeName.trim(); timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); try{ if ("ceylon.language.Nothing".equals(typeName)) { return new NothingType(typeFactory); } else if ("java.lang.Throwable".equals(typeName)) { // FIXME: this being here is highly dubious return convertToDeclaration(modules.getLanguageModule(), "ceylon.language.Exception", declarationType); } ClassMirror classMirror = lookupClassMirror(module, typeName); if (classMirror == null) { // special case when bootstrapping because we may need to pull the decl from the typechecked model if(isBootstrap && typeName.startsWith(CEYLON_LANGUAGE+".")){ ProducedType languageType = findLanguageModuleDeclarationForBootstrap(typeName); if(languageType != null) return languageType.getDeclaration(); } throw new ModelResolutionException("Failed to resolve "+typeName); } // we only allow source loading when it's java code we're compiling in the same go // (well, technically before the ceylon code) if(classMirror.isLoadedFromSource() && !classMirror.isJavaSource()) return null; return convertToDeclaration(classMirror, declarationType); }finally{ timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } protected TypeParameter safeLookupTypeParameter(Scope scope, String name) { TypeParameter param = lookupTypeParameter(scope, name); if(param == null) throw new ModelResolutionException("Type param "+name+" not found in "+scope); return param; } private TypeParameter lookupTypeParameter(Scope scope, String name) { if(scope instanceof Method){ Method m = (Method) scope; for(TypeParameter param : m.getTypeParameters()){ if(param.getName().equals(name)) return param; } if (!m.isToplevel()) { // look it up in its container return lookupTypeParameter(scope.getContainer(), name); } else { // not found return null; } }else if(scope instanceof ClassOrInterface || scope instanceof TypeAlias){ TypeDeclaration decl = (TypeDeclaration) scope; for(TypeParameter param : decl.getTypeParameters()){ if(param.getName().equals(name)) return param; } if (!decl.isToplevel()) { // look it up in its container return lookupTypeParameter(scope.getContainer(), name); } else { // not found return null; } }else throw new ModelResolutionException("Type param "+name+" lookup not supported for scope "+scope); } // // Packages public synchronized LazyPackage findExistingPackage(Module module, String pkgName){ String quotedPkgName = Util.quoteJavaKeywords(pkgName); LazyPackage pkg = findCachedPackage(module, quotedPkgName); if(pkg != null) return pkg; // special case for the jdk module String moduleName = module.getNameAsString(); if(AbstractModelLoader.isJDKModule(moduleName)){ if(JDKUtils.isJDKPackage(moduleName, pkgName) || JDKUtils.isOracleJDKPackage(moduleName, pkgName)){ return findOrCreatePackage(module, pkgName); } return null; } // only create it if it exists if(loadPackage(module, pkgName, false)){ return findOrCreatePackage(module, pkgName); } return null; } private LazyPackage findCachedPackage(Module module, String quotedPkgName) { LazyPackage pkg = packagesByName.get(cacheKeyByModule(module, quotedPkgName)); if(pkg != null){ // only return it if it matches the module we're looking for, because if it doesn't we have an issue already logged // for a direct dependency on same module different versions logged, so no need to confuse this further if(module != null && pkg.getModule() != null && !module.equals(pkg.getModule())) return null; return pkg; } return null; } public synchronized LazyPackage findOrCreatePackage(Module module, final String pkgName) { String quotedPkgName = Util.quoteJavaKeywords(pkgName); LazyPackage pkg = findCachedPackage(module, quotedPkgName); if(pkg != null) return pkg; // try to find it from the module, perhaps it already got created and we didn't catch it if(module instanceof LazyModule){ pkg = (LazyPackage) ((LazyModule) module).findPackageNoLazyLoading(pkgName); }else if(module != null){ pkg = (LazyPackage) module.getDirectPackage(pkgName); } boolean isNew = pkg == null; if(pkg == null){ pkg = new LazyPackage(this); // FIXME: some refactoring needed pkg.setName(pkgName == null ? Collections.<String>emptyList() : Arrays.asList(pkgName.split("\\."))); } packagesByName.put(cacheKeyByModule(module, quotedPkgName), pkg); // only bind it if we already have a module if(isNew && module != null){ pkg.setModule(module); if(module instanceof LazyModule) ((LazyModule) module).addPackage(pkg); else module.getPackages().add(pkg); } // only load package descriptors for new packages after a certain phase if(packageDescriptorsNeedLoading) loadPackageDescriptor(pkg); return pkg; } public synchronized void loadPackageDescriptors() { for(Package pkg : packagesByName.values()){ loadPackageDescriptor(pkg); } packageDescriptorsNeedLoading = true; } private void loadPackageDescriptor(Package pkg) { // Don't try to load a package descriptor for ceylon.language // if we're bootstrapping if (isBootstrap && pkg.getQualifiedNameString().startsWith("ceylon.language")) { return; } // let's not load package descriptors for Java modules if(pkg.getModule() != null && ((LazyModule)pkg.getModule()).isJava()){ pkg.setShared(true); return; } String quotedQualifiedName = Util.quoteJavaKeywords(pkg.getQualifiedNameString()); // FIXME: not sure the toplevel package can have a package declaration String className = quotedQualifiedName.isEmpty() ? "package" : quotedQualifiedName + ".package"; logVerbose("[Trying to look up package from "+className+"]"); Module module = pkg.getModule(); if(module == null) throw new RuntimeException("Assertion failed: module is null for package "+pkg.getNameAsString()); ClassMirror packageClass = loadClass(module, quotedQualifiedName, className); if(packageClass == null){ logVerbose("[Failed to complete "+className+"]"); // missing: leave it private return; } // did we compile it from source or class? if(packageClass.isLoadedFromSource()){ // must have come from source, in which case we walked it and // loaded its values already logVerbose("[We are compiling the package "+className+"]"); return; } loadCompiledPackage(packageClass, pkg); } private void loadCompiledPackage(ClassMirror packageClass, Package pkg) { String name = getAnnotationStringValue(packageClass, CEYLON_PACKAGE_ANNOTATION, "name"); Boolean shared = getAnnotationBooleanValue(packageClass, CEYLON_PACKAGE_ANNOTATION, "shared"); // FIXME: validate the name? if(name == null || name.isEmpty()){ logWarning("Package class "+pkg.getQualifiedNameString()+" contains no name, ignoring it"); return; } if(shared == null){ logWarning("Package class "+pkg.getQualifiedNameString()+" contains no shared, ignoring it"); return; } pkg.setShared(shared); } protected Module lookupModuleInternal(String packageName) { // FIXME: this does not work for multiple modules with same name for(Module module : modules.getListOfModules()){ // don't try the default module because it will always say yes if(module.isDefault()) continue; if(module instanceof LazyModule){ if(((LazyModule)module).containsPackage(packageName)) return module; }else if(isSubPackage(module.getNameAsString(), packageName)){ return module; } } if(packageName.startsWith("com.redhat.ceylon.compiler.java.runtime") || packageName.startsWith("com.redhat.ceylon.compiler.java.language")){ return getLanguageModule(); } return modules.getDefaultModule(); } private boolean isSubPackage(String moduleName, String pkgName) { return pkgName.equals(moduleName) || pkgName.startsWith(moduleName+"."); } // // Modules /** * Finds or creates a new module. This is mostly useful to force creation of modules such as jdk * or ceylon.language modules. */ protected synchronized Module findOrCreateModule(String moduleName, String version) { // FIXME: we don't have any version??? If not this should be private boolean isJava = false; boolean defaultModule = false; // make sure it isn't loaded Module module = getLoadedModule(moduleName); if(module != null) return module; if(JDKUtils.isJDKModule(moduleName) || JDKUtils.isOracleJDKModule(moduleName)){ isJava = true; } java.util.List<String> moduleNameList = Arrays.asList(moduleName.split("\\.")); module = moduleManager.getOrCreateModule(moduleNameList, version); // make sure that when we load the ceylon language module we set it to where // the typechecker will look for it if(moduleName.equals(CEYLON_LANGUAGE) && modules.getLanguageModule() == null){ modules.setLanguageModule(module); } // TRICKY We do this only when isJava is true to prevent resetting // the value to false by mistake. LazyModule get's created with // this attribute to false by default, so it should work if (isJava && module instanceof LazyModule) { ((LazyModule)module).setJava(true); } // FIXME: this can't be that easy. module.setAvailable(true); module.setDefault(defaultModule); return module; } public synchronized boolean loadCompiledModule(Module module) { if(module.isDefault()) return false; String pkgName = module.getNameAsString(); if(pkgName.isEmpty()) return false; String moduleClassName = pkgName + ".module"; logVerbose("[Trying to look up module from "+moduleClassName+"]"); ClassMirror moduleClass = loadClass(module, pkgName, moduleClassName); if(moduleClass != null){ // load its module annotation return loadCompiledModule(module, moduleClass, moduleClassName); } // give up return false; } private boolean loadCompiledModule(Module module, ClassMirror moduleClass, String moduleClassName) { String name = getAnnotationStringValue(moduleClass, CEYLON_MODULE_ANNOTATION, "name"); String version = getAnnotationStringValue(moduleClass, CEYLON_MODULE_ANNOTATION, "version"); if(name == null || name.isEmpty()){ logWarning("Module class "+moduleClassName+" contains no name, ignoring it"); return false; } if(!name.equals(module.getNameAsString())){ logWarning("Module class "+moduleClassName+" declares an invalid name: "+name+". It should be: "+module.getNameAsString()); return false; } if(version == null || version.isEmpty()){ logWarning("Module class "+moduleClassName+" contains no version, ignoring it"); return false; } if(!version.equals(module.getVersion())){ logWarning("Module class "+moduleClassName+" declares an invalid version: "+version+". It should be: "+module.getVersion()); return false; } int major = getAnnotationIntegerValue(moduleClass, CEYLON_CEYLON_ANNOTATION, "major", 0); int minor = getAnnotationIntegerValue(moduleClass, CEYLON_CEYLON_ANNOTATION, "minor", 0); module.setMajor(major); module.setMinor(minor); List<AnnotationMirror> imports = getAnnotationArrayValue(moduleClass, CEYLON_MODULE_ANNOTATION, "dependencies"); if(imports != null){ for (AnnotationMirror importAttribute : imports) { String dependencyName = (String) importAttribute.getValue("name"); if (dependencyName != null) { String dependencyVersion = (String) importAttribute.getValue("version"); Module dependency = moduleManager.getOrCreateModule(ModuleManager.splitModuleName(dependencyName), dependencyVersion); Boolean optionalVal = (Boolean) importAttribute.getValue("optional"); Boolean exportVal = (Boolean) importAttribute.getValue("export"); ModuleImport moduleImport = moduleManager.findImport(module, dependency); if (moduleImport == null) { boolean optional = optionalVal != null && optionalVal; boolean export = exportVal != null && exportVal; moduleImport = new ModuleImport(dependency, optional, export); module.getImports().add(moduleImport); } } } } module.setAvailable(true); modules.getListOfModules().add(module); Module languageModule = modules.getLanguageModule(); module.setLanguageModule(languageModule); if(module != languageModule){ ModuleImport moduleImport = moduleManager.findImport(module, languageModule); if (moduleImport == null) { moduleImport = new ModuleImport(languageModule, false, false); module.getImports().add(moduleImport); } } return true; } // // Utils for loading type info from the model @SuppressWarnings("unchecked") private <T> List<T> getAnnotationArrayValue(AnnotatedMirror mirror, String type, String field) { return (List<T>) getAnnotationValue(mirror, type, field); } @SuppressWarnings("unchecked") private <T> List<T> getAnnotationArrayValue(AnnotatedMirror mirror, String type) { return (List<T>) getAnnotationValue(mirror, type); } private String getAnnotationStringValue(AnnotatedMirror mirror, String type) { return getAnnotationStringValue(mirror, type, "value"); } private String getAnnotationStringValue(AnnotatedMirror mirror, String type, String field) { return (String) getAnnotationValue(mirror, type, field); } private TypeMirror getAnnotationClassValue(AnnotatedMirror mirror, String type, String field) { return (TypeMirror) getAnnotationValue(mirror, type, field); } private List<Short> getAnnotationShortArrayValue(AnnotatedMirror mirror, String type, String field) { return getAnnotationArrayValue(mirror, type, field); } private Boolean getAnnotationBooleanValue(AnnotatedMirror mirror, String type, String field) { return (Boolean) getAnnotationValue(mirror, type, field); } private int getAnnotationIntegerValue(AnnotatedMirror mirror, String type, String field, int defaultValue) { Integer val = (Integer) getAnnotationValue(mirror, type, field); return val != null ? val : defaultValue; } private List<TypeMirror> getAnnotationClassValues(AnnotationMirror annotation, String field) { return (List<TypeMirror>)annotation.getValue(field); } private List<String> getAnnotationStringValues(AnnotationMirror annotation, String field) { return (List<String>)annotation.getValue(field); } private List<Integer> getAnnotationIntegerValues(AnnotationMirror annotation, String field) { return (List<Integer>)annotation.getValue(field); } private List<Boolean> getAnnotationBooleanValues(AnnotationMirror annotation, String field) { return (List<Boolean>)annotation.getValue(field); } private List<Long> getAnnotationLongValues(AnnotationMirror annotation, String field) { return (List<Long>)annotation.getValue(field); } private List<Double> getAnnotationDoubleValues(AnnotationMirror annotation, String field) { return (List<Double>)annotation.getValue(field); } private List<AnnotationMirror> getAnnotationAnnoValues(AnnotationMirror annotation, String field) { return (List<AnnotationMirror>)annotation.getValue(field); } private Object getAnnotationValue(AnnotatedMirror mirror, String type) { return getAnnotationValue(mirror, type, "value"); } private Object getAnnotationValue(AnnotatedMirror mirror, String type, String fieldName) { AnnotationMirror annotation = mirror.getAnnotation(type); if(annotation != null){ return annotation.getValue(fieldName); } return null; } // // ModelCompleter @Override public synchronized void complete(LazyInterface iface) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); complete(iface, iface.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } @Override public synchronized void completeTypeParameters(LazyInterface iface) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeTypeParameters(iface, iface.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } @Override public synchronized void complete(LazyClass klass) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); complete(klass, klass.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } @Override public synchronized void completeTypeParameters(LazyClass klass) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeTypeParameters(klass, klass.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } @Override public synchronized void completeTypeParameters(LazyClassAlias lazyClassAlias) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAliasTypeParameters(lazyClassAlias, lazyClassAlias.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } @Override public synchronized void completeTypeParameters(LazyInterfaceAlias lazyInterfaceAlias) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAliasTypeParameters(lazyInterfaceAlias, lazyInterfaceAlias.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } @Override public synchronized void completeTypeParameters(LazyTypeAlias lazyTypeAlias) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAliasTypeParameters(lazyTypeAlias, lazyTypeAlias.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } @Override public synchronized void complete(LazyInterfaceAlias alias) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAlias(alias, alias.classMirror, CEYLON_ALIAS_ANNOTATION); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } @Override public synchronized void complete(LazyClassAlias alias) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAlias(alias, alias.classMirror, CEYLON_ALIAS_ANNOTATION); // must be a class Class declaration = (Class) alias.getExtendedType().getDeclaration(); // copy the parameters from the extended type alias.setParameterList(copyParameterList(alias, declaration)); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } private ParameterList copyParameterList(LazyClassAlias alias, Class declaration) { ParameterList newList = new ParameterList(); // FIXME: multiple param lists? newList.setNamedParametersSupported(declaration.getParameterList().isNamedParametersSupported()); for(Parameter p : declaration.getParameterList().getParameters()){ // FIXME: functionalparams? Parameter newParam = new Parameter(); MethodOrValue mov; if (p.getModel() instanceof Value) { Value value = new Value(); mov = value; } else { Method method = new Method(); mov = method; } mov.setContainer(alias); mov.setUnboxed(p.getModel().getUnboxed()); mov.setUncheckedNullType(p.getModel().hasUncheckedNullType()); mov.setUnit(p.getModel().getUnit()); mov.setType(p.getModel().getProducedTypedReference(alias.getExtendedType(), Collections.<ProducedType>emptyList()).getType()); newParam.setModel(mov); newParam.setName(p.getName()); DeclarationVisitor.setVisibleScope(mov); newParam.setDeclaration(alias); newParam.setSequenced(p.isSequenced()); alias.addMember(mov); newList.getParameters().add(newParam); } return newList; } @Override public synchronized void complete(LazyTypeAlias alias) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAlias(alias, alias.classMirror, CEYLON_TYPE_ALIAS_ANNOTATION); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } private void completeLazyAliasTypeParameters(TypeDeclaration alias, ClassMirror mirror) { // type parameters setTypeParameters(alias, mirror); } private void completeLazyAlias(TypeDeclaration alias, ClassMirror mirror, String aliasAnnotationName) { // now resolve the extended type AnnotationMirror aliasAnnotation = mirror.getAnnotation(aliasAnnotationName); String extendedTypeString = (String) aliasAnnotation.getValue(); ProducedType extendedType = decodeType(extendedTypeString, alias, Decl.getModuleContainer(alias), "alias target"); alias.setExtendedType(extendedType); } private void completeTypeParameters(ClassOrInterface klass, ClassMirror classMirror) { setTypeParameters(klass, classMirror); } private void complete(ClassOrInterface klass, ClassMirror classMirror) { Map<MethodMirror, List<MethodMirror>> variables = new HashMap<MethodMirror, List<MethodMirror>>(); boolean isFromJDK = isFromJDK(classMirror); boolean isCeylon = (classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null); // now that everything has containers, do the inner classes if(klass instanceof Class == false || !((Class)klass).isOverloaded()){ // this will not load inner classes of overloads, but that's fine since we want them in the // abstracted super class (the real one) addInnerClasses(klass, classMirror); } // Java classes with multiple constructors get turned into multiple Ceylon classes // Here we get the specific constructor that was assigned to us (if any) MethodMirror constructor = null; if (klass instanceof LazyClass) { constructor = ((LazyClass)klass).getConstructor(); } // Turn a list of possibly overloaded methods into a map // of lists that contain methods with the same name Map<String, List<MethodMirror>> methods = new LinkedHashMap<String, List<MethodMirror>>(); for(MethodMirror methodMirror : classMirror.getDirectMethods()){ // We skip members marked with @Ignore if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(methodMirror.isStaticInit()) continue; if(isCeylon && methodMirror.isStatic()) continue; // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !methodMirror.isPublic()) continue; String methodName = methodMirror.getName(); List<MethodMirror> homonyms = methods.get(methodName); if (homonyms == null) { homonyms = new LinkedList<MethodMirror>(); methods.put(methodName, homonyms); } homonyms.add(methodMirror); } // Add the methods for(List<MethodMirror> methodMirrors : methods.values()){ boolean isOverloaded = methodMirrors.size() > 1; List<Declaration> overloads = (isOverloaded) ? new ArrayList<Declaration>(methodMirrors.size()) : null; for (MethodMirror methodMirror : methodMirrors) { String methodName = methodMirror.getName(); if(methodMirror.isConstructor()) { break; } else if(isGetter(methodMirror)) { // simple attribute addValue(klass, methodMirror, getJavaAttributeName(methodName), isCeylon); } else if(isSetter(methodMirror)) { // We skip setters for now and handle them later variables.put(methodMirror, methodMirrors); } else if(isHashAttribute(methodMirror)) { // ERASURE // Un-erasing 'hash' attribute from 'hashCode' method addValue(klass, methodMirror, "hash", isCeylon); } else if(isStringAttribute(methodMirror)) { // ERASURE // Un-erasing 'string' attribute from 'toString' method addValue(klass, methodMirror, "string", isCeylon); } else { // normal method Method m = addMethod(klass, methodMirror, isCeylon, isOverloaded); if (isOverloaded) { overloads.add(m); } } } if (overloads != null && !overloads.isEmpty()) { // We create an extra "abstraction" method for overloaded methods Method abstractionMethod = addMethod(klass, methodMirrors.get(0), false, false); abstractionMethod.setAbstraction(true); abstractionMethod.setOverloads(overloads); abstractionMethod.setType(new UnknownType(typeFactory).getType()); } } for(FieldMirror fieldMirror : classMirror.getDirectFields()){ // We skip members marked with @Ignore if(fieldMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(isCeylon && fieldMirror.isStatic()) continue; // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !fieldMirror.isPublic()) continue; String name = fieldMirror.getName(); // skip the field if "we've already got one" if(klass.getDirectMember(name, null, false) != null) continue; - addValue(klass, fieldMirror, isCeylon); + if (!"string".equals(fieldMirror.getName()) && ! "hash".equals(fieldMirror.getName())) { + addValue(klass, fieldMirror, isCeylon); + } } // Having loaded methods and values, we can now set the constructor parameters if(constructor != null && (!(klass instanceof LazyClass) || !((LazyClass)klass).isTopLevelObjectType())) setParameters((Class)klass, constructor, isCeylon, klass); // Now marry-up attributes and parameters) if (klass instanceof Class) { for (Declaration m : klass.getMembers()) { if (Decl.isValue(m)) { Value v = (Value)m; Parameter p = ((Class)klass).getParameter(v.getName()); if (p != null) { p.setHidden(true); } } } } // Now mark all Values for which Setters exist as variable for(Entry<MethodMirror, List<MethodMirror>> setterEntry : variables.entrySet()){ MethodMirror setter = setterEntry.getKey(); String name = getJavaAttributeName(setter.getName()); Declaration decl = klass.getMember(name, null, false); boolean foundGetter = false; // skip Java fields, which we only get if there is no getter method, in that case just add the setter method if (decl instanceof Value && decl instanceof FieldValue == false) { Value value = (Value)decl; VariableMirror setterParam = setter.getParameters().get(0); ProducedType paramType = obtainType(setterParam.getType(), setterParam, klass, Decl.getModuleContainer(klass), VarianceLocation.INVARIANT, "setter '"+setter.getName()+"'", klass); // only add the setter if it has exactly the same type as the getter if(paramType.isExactly(value.getType())){ foundGetter = true; value.setVariable(true); if(decl instanceof JavaBeanValue) ((JavaBeanValue)decl).setSetterName(setter.getName()); }else logVerbose("Setter parameter type for "+name+" does not match corresponding getter type, adding setter as a method"); } if(!foundGetter){ // it was not a setter, it was a method, let's add it as such addMethod(klass, setter, isCeylon, false); } } // In some cases, where all constructors are ignored, we can end up with no constructor, so // pretend we have one which takes no parameters (eg. ceylon.language.String). if(klass instanceof Class && !((Class) klass).isAbstraction() && !klass.isAnonymous() && ((Class) klass).getParameterList() == null){ ((Class) klass).setParameterList(new ParameterList()); } setExtendedType(klass, classMirror); setSatisfiedTypes(klass, classMirror); setCaseTypes(klass, classMirror); fillRefinedDeclarations(klass); if(isCeylon) checkReifiedGenericsForMethods(klass, classMirror); setAnnotations(klass, classMirror); } private void checkReifiedGenericsForMethods(ClassOrInterface klass, ClassMirror classMirror) { for(Declaration member : klass.getMembers()){ if(member instanceof JavaMethod == false) continue; MethodMirror mirror = ((JavaMethod)member).mirror; if(AbstractTransformer.supportsReified(member)){ checkReifiedTypeDescriptors(mirror.getTypeParameters().size(), classMirror, mirror, false); } } } private boolean isFromJDK(ClassMirror classMirror) { String pkgName = classMirror.getPackage().getQualifiedName(); return JDKUtils.isJDKAnyPackage(pkgName) || JDKUtils.isOracleJDKAnyPackage(pkgName); } private void setAnnotations(Declaration decl, AnnotatedMirror classMirror) { List<AnnotationMirror> annotations = getAnnotationArrayValue(classMirror, CEYLON_ANNOTATIONS_ANNOTATION); if(annotations != null) { for(AnnotationMirror annotation : annotations){ decl.getAnnotations().add(readModelAnnotation(annotation)); } } // Add a ceylon deprecated("") if it's annotated with java.lang.Deprecated // and doesn't already have the ceylon annotation if (classMirror.getAnnotation(JAVA_DEPRECATED_ANNOTATION) != null) { boolean hasCeylonDeprecated = false; for(Annotation a : decl.getAnnotations()) { if (a.getName().equals("deprecated")) { hasCeylonDeprecated = true; break; } } if (!hasCeylonDeprecated) { Annotation modelAnnotation = new Annotation(); modelAnnotation.setName("deprecated"); modelAnnotation.getPositionalArguments().add(""); decl.getAnnotations().add(modelAnnotation); } } } private Annotation readModelAnnotation(AnnotationMirror annotation) { Annotation modelAnnotation = new Annotation(); modelAnnotation.setName((String) annotation.getValue()); @SuppressWarnings("unchecked") List<String> arguments = (List<String>) annotation.getValue("arguments"); if(arguments != null){ modelAnnotation.getPositionalArguments().addAll(arguments); }else{ @SuppressWarnings("unchecked") List<AnnotationMirror> namedArguments = (List<AnnotationMirror>) annotation.getValue("namedArguments"); if(namedArguments != null){ for(AnnotationMirror namedArgument : namedArguments){ String argName = (String) namedArgument.getValue("name"); String argValue = (String) namedArgument.getValue("value"); modelAnnotation.getNamedArguments().put(argName, argValue); } } } return modelAnnotation; } private void addInnerClasses(ClassOrInterface klass, ClassMirror classMirror) { AnnotationMirror membersAnnotation = classMirror.getAnnotation(CEYLON_MEMBERS_ANNOTATION); if(membersAnnotation == null) addInnerClassesFromMirror(klass, classMirror); else addInnerClassesFromAnnotation(klass, membersAnnotation); } private void addInnerClassesFromAnnotation(ClassOrInterface klass, AnnotationMirror membersAnnotation) { List<AnnotationMirror> members = (List<AnnotationMirror>) membersAnnotation.getValue(); for(AnnotationMirror member : members){ TypeMirror javaClassMirror = (TypeMirror)member.getValue("klass"); String javaClassName = javaClassMirror.getQualifiedName(); Declaration innerDecl = convertToDeclaration(Decl.getModuleContainer(klass), javaClassName, DeclarationType.TYPE); if(innerDecl == null) throw new ModelResolutionException("Failed to load inner type " + javaClassName + " for outer type " + klass.getQualifiedNameString()); } } /** * Allows subclasses to do something to the class name */ protected String assembleJavaClass(String javaClass, String packageName) { return javaClass; } private void addInnerClassesFromMirror(ClassOrInterface klass, ClassMirror classMirror) { boolean isJDK = isFromJDK(classMirror); for(ClassMirror innerClass : classMirror.getDirectInnerClasses()){ // We skip members marked with @Ignore if(innerClass.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; // We skip anonymous inner classes if(innerClass.isAnonymous()) continue; // We skip private classes, otherwise the JDK has a ton of unresolved things if(isJDK && !innerClass.isPublic()) continue; Declaration innerDecl = convertToDeclaration(innerClass, DeclarationType.TYPE); // no need to set its container as that's now handled by convertToDeclaration } } private Method addMethod(ClassOrInterface klass, MethodMirror methodMirror, boolean isCeylon, boolean isOverloaded) { JavaMethod method = new JavaMethod(methodMirror); method.setContainer(klass); method.setRealName(methodMirror.getName()); method.setUnit(klass.getUnit()); method.setOverloaded(isOverloaded); ProducedType type = null; try{ setMethodOrValueFlags(klass, methodMirror, method, isCeylon); }catch(ModelResolutionException x){ // collect an error in its type type = logModelResolutionException(x, klass, "method '"+methodMirror.getName()+"' (checking if it is an overriding method"); } method.setName(Util.strip(methodMirror.getName(), isCeylon, method.isShared())); method.setDefaultedAnnotation(methodMirror.isDefault()); // type params first setTypeParameters(method, methodMirror); // now its parameters if(isEqualsMethod(methodMirror)) setEqualsParameters(method, methodMirror); else setParameters(method, methodMirror, isCeylon, klass); // and its return type // do not log an additional error if we had one from checking if it was overriding if(type == null) type = obtainType(methodMirror.getReturnType(), methodMirror, method, Decl.getModuleContainer(method), VarianceLocation.COVARIANT, "method '"+methodMirror.getName()+"'", klass); method.setType(type); method.setUncheckedNullType((!isCeylon && !methodMirror.getReturnType().isPrimitive()) || isUncheckedNull(methodMirror)); method.setDeclaredAnything(methodMirror.isDeclaredVoid()); type.setRaw(isRaw(Decl.getModuleContainer(klass), methodMirror.getReturnType())); markUnboxed(method, methodMirror.getReturnType()); markTypeErased(method, methodMirror, methodMirror.getReturnType()); setAnnotations(method, methodMirror); klass.getMembers().add(method); return method; } private void fillRefinedDeclarations(ClassOrInterface klass) { for(Declaration member : klass.getMembers()){ // do not trigger a type load (by calling isActual()) for Java inner classes since they // can never be actual if(member instanceof ClassOrInterface && !Decl.isCeylon((ClassOrInterface)member)) continue; if(member.isActual()){ member.setRefinedDeclaration(findRefinedDeclaration(klass, member.getName(), getSignature(member), false)); } } } private List<ProducedType> getSignature(Declaration decl) { List<ProducedType> result = null; if (decl instanceof Functional) { Functional func = (Functional)decl; if (func.getParameterLists().size() > 0) { List<Parameter> params = func.getParameterLists().get(0).getParameters(); result = new ArrayList<ProducedType>(params.size()); for (Parameter p : params) { result.add(p.getType()); } } } return result; } private Declaration findRefinedDeclaration(ClassOrInterface decl, String name, List<ProducedType> signature, boolean ellipsis) { Declaration refinedDeclaration = decl.getRefinedMember(name, signature, ellipsis); if(refinedDeclaration == null) throw new ModelResolutionException("Failed to find refined declaration for "+name); return refinedDeclaration; } private boolean isStartOfJavaBeanPropertyName(char c){ return Character.isUpperCase(c) || c == '_'; } private boolean isGetter(MethodMirror methodMirror) { String name = methodMirror.getName(); boolean matchesGet = name.length() > 3 && name.startsWith("get") && isStartOfJavaBeanPropertyName(name.charAt(3)) && !"getString".equals(name) && !"getHash".equals(name); boolean matchesIs = name.length() > 2 && name.startsWith("is") && isStartOfJavaBeanPropertyName(name.charAt(2)) && !"isString".equals(name) && !"isHash".equals(name); boolean hasNoParams = methodMirror.getParameters().size() == 0; boolean hasNonVoidReturn = (methodMirror.getReturnType().getKind() != TypeKind.VOID); return (matchesGet || matchesIs) && hasNoParams && hasNonVoidReturn; } private boolean isSetter(MethodMirror methodMirror) { String name = methodMirror.getName(); boolean matchesSet = name.length() > 3 && name.startsWith("set") && isStartOfJavaBeanPropertyName(name.charAt(3)) && !"setString".equals(name) && !"setHash".equals(name); boolean hasOneParam = methodMirror.getParameters().size() == 1; boolean hasVoidReturn = (methodMirror.getReturnType().getKind() == TypeKind.VOID); return matchesSet && hasOneParam && hasVoidReturn; } private boolean isHashAttribute(MethodMirror methodMirror) { String name = methodMirror.getName(); boolean matchesName = "hashCode".equals(name); boolean hasNoParams = methodMirror.getParameters().size() == 0; return matchesName && hasNoParams; } private boolean isStringAttribute(MethodMirror methodMirror) { String name = methodMirror.getName(); boolean matchesName = "toString".equals(name); boolean hasNoParams = methodMirror.getParameters().size() == 0; return matchesName && hasNoParams; } private boolean isEqualsMethod(MethodMirror methodMirror) { String name = methodMirror.getName(); if(!"equals".equals(name) || methodMirror.getParameters().size() != 1) return false; VariableMirror param = methodMirror.getParameters().get(0); return sameType(param.getType(), OBJECT_TYPE); } private void setEqualsParameters(Method decl, MethodMirror methodMirror) { ParameterList parameters = new ParameterList(); decl.addParameterList(parameters); Parameter parameter = new Parameter(); Value value = new Value(); parameter.setModel(value); value.setInitializerParameter(parameter); value.setUnit(decl.getUnit()); value.setContainer((Scope) decl); parameter.setName("that"); value.setName("that"); value.setType(getNonPrimitiveType(CEYLON_OBJECT_TYPE, decl, VarianceLocation.INVARIANT)); parameter.setDeclaration((Declaration) decl); parameters.getParameters().add(parameter); } private String getJavaAttributeName(String getterName) { if (getterName.startsWith("get") || getterName.startsWith("set")) { return getJavaBeanName(getterName.substring(3)); } else if (getterName.startsWith("is")) { // Starts with "is" return getJavaBeanName(getterName.substring(2)); } else { throw new RuntimeException("Illegal java getter/setter name"); } } private String getJavaBeanName(String name) { // See https://github.com/ceylon/ceylon-compiler/issues/340 // make it lowercase until the first non-uppercase char[] newName = name.toCharArray(); for(int i=0;i<newName.length;i++){ char c = newName[i]; if(Character.isLowerCase(c)){ // if we had more than one upper-case, we leave the last uppercase: getURLDecoder -> urlDecoder if(i > 1){ newName[i-1] = Character.toUpperCase(newName[i-1]); } break; } newName[i] = Character.toLowerCase(c); } return new String(newName); } private void addValue(ClassOrInterface klass, FieldMirror fieldMirror, boolean isCeylon) { // make sure it's a FieldValue so we can figure it out in the backend Value value = new FieldValue(fieldMirror.getName()); value.setContainer(klass); // use the name annotation if present (used by Java arrays) String nameAnnotation = getAnnotationStringValue(fieldMirror, CEYLON_NAME_ANNOTATION); value.setName(nameAnnotation != null ? nameAnnotation : fieldMirror.getName()); value.setUnit(klass.getUnit()); value.setShared(fieldMirror.isPublic() || fieldMirror.isProtected() || fieldMirror.isDefaultAccess()); value.setProtectedVisibility(fieldMirror.isProtected()); value.setPackageVisibility(fieldMirror.isDefaultAccess()); value.setStaticallyImportable(fieldMirror.isStatic()); // field can't be abstract or interface, so not formal // can we override fields? good question. Not really, but from an external point of view? // FIXME: figure this out: (default) // FIXME: for the same reason, can it be an overriding field? (actual) value.setVariable(!fieldMirror.isFinal()); // figure out if it's an enum subtype in a final static field if(fieldMirror.getType().getKind() == TypeKind.DECLARED && fieldMirror.getType().getDeclaredClass() != null && fieldMirror.getType().getDeclaredClass().isEnum() && fieldMirror.isFinal() && fieldMirror.isStatic()) value.setEnumValue(true); ProducedType type = obtainType(fieldMirror.getType(), fieldMirror, klass, Decl.getModuleContainer(klass), VarianceLocation.INVARIANT, "field '"+value.getName()+"'", klass); value.setType(type); value.setUncheckedNullType((!isCeylon && !fieldMirror.getType().isPrimitive()) || isUncheckedNull(fieldMirror)); type.setRaw(isRaw(Decl.getModuleContainer(klass), fieldMirror.getType())); markUnboxed(value, fieldMirror.getType()); markTypeErased(value, fieldMirror, fieldMirror.getType()); setAnnotations(value, fieldMirror); klass.getMembers().add(value); } private boolean isRaw(Module module, TypeMirror type) { // dirty hack to get rid of bug where calling type.isRaw() on a ceylon type we are going to compile would complete() it, which // would try to parse its file. For ceylon types we don't need the class file info we can query it // See https://github.com/ceylon/ceylon-compiler/issues/1085 switch(type.getKind()){ case ARRAY: // arrays are never raw case BOOLEAN: case BYTE: case CHAR: case DOUBLE: case ERROR: case FLOAT: case INT: case LONG: case NULL: case SHORT: case TYPEVAR: case VOID: case WILDCARD: return false; case DECLARED: ClassMirror klass = type.getDeclaredClass(); if(klass.isJavaSource()){ // I suppose this should work return type.isRaw(); } List<String> path = new LinkedList<String>(); String pkgName = klass.getPackage().getQualifiedName(); String qualifiedName = klass.getQualifiedName(); String relativeName = pkgName.isEmpty() ? qualifiedName : qualifiedName.substring(pkgName.length()+1); for(String name : relativeName.split("[\\$\\.]")){ if(!name.isEmpty()){ path.add(0, klass.getName()); } } if(path.size() > 1){ // find the proper class mirror for the container klass = loadClass(module, pkgName, path.get(0)); if(klass == null) return false; } if(!path.isEmpty() && klass.isLoadedFromSource()){ // we need to find its model Scope scope = packagesByName.get(cacheKeyByModule(module, pkgName)); if(scope == null) return false; for(String name : path){ Declaration decl = scope.getDirectMember(name, null, false); if(decl == null) return false; // if we get a value, we want its type if(Decl.isValue(decl) && ((Value)decl).getTypeDeclaration().getName().equals(name)) decl = ((Value)decl).getTypeDeclaration(); if(decl instanceof TypeDeclaration == false) return false; scope = (TypeDeclaration)decl; } TypeDeclaration typeDecl = (TypeDeclaration) scope; return !typeDecl.getTypeParameters().isEmpty() && type.getTypeArguments().isEmpty(); } return type.isRaw(); default: return false; } } private void addValue(ClassOrInterface klass, MethodMirror methodMirror, String methodName, boolean isCeylon) { JavaBeanValue value = new JavaBeanValue(); value.setGetterName(methodMirror.getName()); value.setContainer(klass); value.setUnit(klass.getUnit()); ProducedType type = null; try{ setMethodOrValueFlags(klass, methodMirror, value, isCeylon); }catch(ModelResolutionException x){ // collect an error in its type type = logModelResolutionException(x, klass, "getter '"+methodName+"' (checking if it is an overriding method"); } value.setName(Util.strip(methodName, isCeylon, value.isShared())); // do not log an additional error if we had one from checking if it was overriding if(type == null) type = obtainType(methodMirror.getReturnType(), methodMirror, klass, Decl.getModuleContainer(klass), VarianceLocation.INVARIANT, "getter '"+methodName+"'", klass); value.setType(type); // special case for hash attributes which we want to pretend are of type long internally if(value.isShared() && methodName.equals("hash")) type.setUnderlyingType("long"); value.setUncheckedNullType((!isCeylon && !methodMirror.getReturnType().isPrimitive()) || isUncheckedNull(methodMirror)); type.setRaw(isRaw(Decl.getModuleContainer(klass), methodMirror.getReturnType())); markUnboxed(value, methodMirror.getReturnType()); markTypeErased(value, methodMirror, methodMirror.getReturnType()); setAnnotations(value, methodMirror); klass.getMembers().add(value); } private boolean isUncheckedNull(AnnotatedMirror methodMirror) { Boolean unchecked = getAnnotationBooleanValue(methodMirror, CEYLON_TYPE_INFO_ANNOTATION, "uncheckedNull"); return unchecked != null && unchecked.booleanValue(); } private void setMethodOrValueFlags(ClassOrInterface klass, MethodMirror methodMirror, MethodOrValue decl, boolean isCeylon) { decl.setShared(methodMirror.isPublic() || methodMirror.isProtected() || methodMirror.isDefaultAccess()); decl.setProtectedVisibility(methodMirror.isProtected()); decl.setPackageVisibility(methodMirror.isDefaultAccess()); if(decl instanceof Value){ setValueTransientLateFlags((Value)decl, methodMirror, isCeylon); } if(// for class members we rely on abstract bit (klass instanceof Class && methodMirror.isAbstract()) // Java interfaces are formal || (klass instanceof Interface && !((LazyInterface)klass).isCeylon()) // For Ceylon interfaces we rely on annotation || methodMirror.getAnnotation(CEYLON_LANGUAGE_FORMAL_ANNOTATION) != null) { decl.setFormal(true); } else { if (// for class members we rely on final/static bits (klass instanceof Class && !methodMirror.isFinal() && !methodMirror.isStatic()) // Java interfaces are never final || (klass instanceof Interface && !((LazyInterface)klass).isCeylon()) // For Ceylon interfaces we rely on annotation || methodMirror.getAnnotation(CEYLON_LANGUAGE_DEFAULT_ANNOTATION) != null){ decl.setDefault(true); } } decl.setStaticallyImportable(methodMirror.isStatic()); if(isOverridingMethod(methodMirror) // For Ceylon interfaces we rely on annotation || (klass instanceof LazyInterface && ((LazyInterface)klass).isCeylon() && methodMirror.getAnnotation(CEYLON_LANGUAGE_ACTUAL_ANNOTATION) != null)){ decl.setActual(true); } } private void setValueTransientLateFlags(Value decl, MethodMirror methodMirror, boolean isCeylon) { if(isCeylon) decl.setTransient(methodMirror.getAnnotation(CEYLON_TRANSIENT_ANNOTATION) != null); else // all Java getters are transient, fields are not decl.setTransient(decl instanceof FieldValue == false); decl.setLate(methodMirror.getAnnotation(CEYLON_LANGUAGE_LATE_ANNOTATION) != null); } private void setExtendedType(ClassOrInterface klass, ClassMirror classMirror) { // look at its super type TypeMirror superClass = classMirror.getSuperclass(); ProducedType extendedType; if(klass instanceof Interface){ // interfaces need to have their superclass set to Object if(superClass == null || superClass.getKind() == TypeKind.NONE) extendedType = getNonPrimitiveType(CEYLON_OBJECT_TYPE, klass, VarianceLocation.INVARIANT); else extendedType = getNonPrimitiveType(superClass, klass, VarianceLocation.INVARIANT); }else{ String className = classMirror.getQualifiedName(); String superClassName = superClass == null ? null : superClass.getQualifiedName(); if(className.equals("ceylon.language.Anything")){ // ceylon.language.Anything has no super type extendedType = null; }else if(className.equals("java.lang.Object")){ // we pretend its superclass is something else, but note that in theory we shouldn't // be seeing j.l.Object at all due to unerasure extendedType = getNonPrimitiveType(CEYLON_BASIC_TYPE, klass, VarianceLocation.INVARIANT); }else{ // read it from annotation first String annotationSuperClassName = getAnnotationStringValue(classMirror, CEYLON_CLASS_ANNOTATION, "extendsType"); if(annotationSuperClassName != null && !annotationSuperClassName.isEmpty()){ extendedType = decodeType(annotationSuperClassName, klass, Decl.getModuleContainer(klass), "extended type"); }else{ // read it from the Java super type // now deal with type erasure, avoid having Object as superclass if("java.lang.Object".equals(superClassName)){ extendedType = getNonPrimitiveType(CEYLON_BASIC_TYPE, klass, VarianceLocation.INVARIANT); }else if(superClass != null){ try{ extendedType = getNonPrimitiveType(superClass, klass, VarianceLocation.INVARIANT); }catch(ModelResolutionException x){ extendedType = logModelResolutionException(x, klass, "Error while resolving extended type of "+klass.getQualifiedNameString()); } }else{ // FIXME: should this be UnknownType? extendedType = null; } } } } if(extendedType != null) klass.setExtendedType(extendedType); } private void setParameters(Functional decl, MethodMirror methodMirror, boolean isCeylon, Scope container) { ParameterList parameters = new ParameterList(); parameters.setNamedParametersSupported(isCeylon); decl.addParameterList(parameters); int parameterCount = methodMirror.getParameters().size(); int parameterIndex = 0; for(VariableMirror paramMirror : methodMirror.getParameters()){ // ignore some parameters if(paramMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; boolean isLastParameter = parameterIndex == parameterCount - 1; boolean isVariadic = isLastParameter && methodMirror.isVariadic(); String paramName = getAnnotationStringValue(paramMirror, CEYLON_NAME_ANNOTATION); // use whatever param name we find as default if(paramName == null) paramName = paramMirror.getName(); Parameter parameter = new Parameter(); parameter.setName(paramName); TypeMirror typeMirror = paramMirror.getType(); ProducedType type; if(isVariadic){ // possibly make it optional TypeMirror variadicType = typeMirror.getComponentType(); // we pretend it's toplevel because we want to get magic string conversion for variadic methods type = obtainType(variadicType, (Scope)decl, TypeLocation.TOPLEVEL, VarianceLocation.CONTRAVARIANT); if(!isCeylon && !variadicType.isPrimitive()){ // Java parameters are all optional unless primitives ProducedType optionalType = getOptionalType(type); optionalType.setUnderlyingType(type.getUnderlyingType()); type = optionalType; } // turn it into a Sequential<T> type = typeFactory.getSequentialType(type); }else{ type = obtainType(typeMirror, paramMirror, (Scope) decl, Decl.getModuleContainer((Scope) decl), VarianceLocation.CONTRAVARIANT, "parameter '"+paramName+"' of method '"+methodMirror.getName()+"'", (Declaration)decl); // variadic params may technically be null in Java, but it Ceylon sequenced params may not // so it breaks the typechecker logic for handling them, and it will always be a case of bugs // in the java side so let's not allow this if(!isCeylon && !typeMirror.isPrimitive()){ // Java parameters are all optional unless primitives ProducedType optionalType = getOptionalType(type); optionalType.setUnderlyingType(type.getUnderlyingType()); type = optionalType; } } MethodOrValue value = null; if (isCeylon && decl instanceof Class){ // For a functional parameter to a class, we can just lookup the member value = (MethodOrValue)((Class)decl).getDirectMember(paramName, null, false); } if (value == null) { // So either decl is not a Class, // or the method or value member of decl is not shared if (paramMirror.getAnnotation(CEYLON_FUNCTIONAL_PARAMETER_ANNOTATION) != null) { // A functional parameter to a method Method method = new Method(); method.setType(typeFactory.getCallableReturnType(type)); // We need to set enough of a parameter list so that the method's full type is correct ParameterList pl = new ParameterList(); for (ProducedType pt : typeFactory.getCallableArgumentTypes(type)) { Parameter p = new Parameter(); Value v = new Value(); v.setType(pt); p.setModel(v); pl.getParameters().add(p); } method.addParameterList(pl); value = method; } else { // A value parameter to a method value = new Value(); value.setType(type); } value.setContainer((Scope) decl); DeclarationVisitor.setVisibleScope(value); value.setUnit(((Element)decl).getUnit()); value.setName(paramName); } value.setInitializerParameter(parameter); parameter.setModel(value); if(paramMirror.getAnnotation(CEYLON_SEQUENCED_ANNOTATION) != null || isVariadic) parameter.setSequenced(true); if(paramMirror.getAnnotation(CEYLON_DEFAULTED_ANNOTATION) != null) parameter.setDefaulted(true); if (parameter.isSequenced() && typeFactory.isNonemptyIterableType(parameter.getType())) { parameter.setAtLeastOne(true); } // if it's variadic, consider the array element type (T[] == T...) for boxing rules markUnboxed(value, isVariadic ? paramMirror.getType().getComponentType() : paramMirror.getType()); parameter.setDeclaration((Declaration) decl); setAnnotations(value, paramMirror); parameters.getParameters().add(parameter); parameterIndex++; } } private ProducedType getOptionalType(ProducedType type) { // we do not use Unit.getOptionalType because it causes lots of lazy loading that ultimately triggers the typechecker's // infinite recursion loop List<ProducedType> list = new ArrayList<ProducedType>(2); list.add(typeFactory.getNullDeclaration().getType()); list.add(type); UnionType ut = new UnionType(typeFactory); ut.setCaseTypes(list); return ut.getType(); } private ProducedType logModelResolutionError(Scope container, String message) { return logModelResolutionException((String)null, container, message); } private ProducedType logModelResolutionException(ModelResolutionException x, Scope container, String message) { return logModelResolutionException(x.getMessage(), container, message); } private ProducedType logModelResolutionException(final String exceptionMessage, Scope container, final String message) { final Module module = Decl.getModuleContainer(container); Runnable errorReporter; if(module != null && !module.isDefault()){ final StringBuilder sb = new StringBuilder(); sb.append("Error while loading the ").append(module.getNameAsString()).append("/").append(module.getVersion()); sb.append(" module:\n "); sb.append(message); if(exceptionMessage != null) sb.append(":\n ").append(exceptionMessage); errorReporter = new Runnable(){ public void run(){ moduleManager.attachErrorToOriginalModuleImport(module, sb.toString()); } }; }else if(exceptionMessage == null){ errorReporter = new Runnable(){ public void run(){ logError(message); } }; }else{ errorReporter = new Runnable(){ public void run(){ logError(message+": "+exceptionMessage); } }; } UnknownType ret = new UnknownType(typeFactory); ret.setErrorReporter(errorReporter); return ret.getType(); } private void markTypeErased(TypedDeclaration decl, AnnotatedMirror typedMirror, TypeMirror type) { if (getAnnotationBooleanValue(typedMirror, CEYLON_TYPE_INFO_ANNOTATION, "erased") == Boolean.TRUE) { decl.setTypeErased(true); } else { decl.setTypeErased(sameType(type, OBJECT_TYPE)); } if(hasTypeParameterWithConstraints(type)) decl.setUntrustedType(true); } private boolean hasTypeParameterWithConstraints(TypeMirror type) { switch(type.getKind()){ case BOOLEAN: case BYTE: case CHAR: case DOUBLE: case FLOAT: case INT: case LONG: case SHORT: case VOID: case WILDCARD: return false; case ARRAY: return hasTypeParameterWithConstraints(type.getComponentType()); case DECLARED: for(TypeMirror ta : type.getTypeArguments()){ if(hasTypeParameterWithConstraints(ta)) return true; } return false; case TYPEVAR: TypeParameterMirror typeParameter = type.getTypeParameter(); return typeParameter != null && hasNonErasedBounds(typeParameter); default: return false; } } private void markUnboxed(TypedDeclaration decl, TypeMirror type) { boolean unboxed = false; if(type.isPrimitive() || type.getKind() == TypeKind.ARRAY || sameType(type, STRING_TYPE) || Util.isUnboxedVoid(decl)) { unboxed = true; } decl.setUnboxed(unboxed); } @Override public synchronized void complete(LazyValue value) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); try{ MethodMirror meth = null; for (MethodMirror m : value.classMirror.getDirectMethods()) { // Do not skip members marked with @Ignore, because the getter is supposed to be ignored if (m.getName().equals( Naming.getGetterName(value)) && m.isStatic() && m.getParameters().size() == 0) { meth = m; } if (m.getName().equals( Naming.getSetterName(value)) && m.isStatic() && m.getParameters().size() == 1) { value.setVariable(true); } } if(meth == null || meth.getReturnType() == null){ value.setType(logModelResolutionError(value.getContainer(), "Error while resolving toplevel attribute "+value.getQualifiedNameString()+": getter method missing")); return; } value.setType(obtainType(meth.getReturnType(), meth, null, Decl.getModuleContainer(value.getContainer()), VarianceLocation.INVARIANT, "toplevel attribute", value)); setValueTransientLateFlags(value, meth, true); setAnnotations(value, meth); markUnboxed(value, meth.getReturnType()); }finally{ timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public synchronized void complete(LazyMethod method) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); try{ MethodMirror meth = null; String lookupName = method.getName(); for(MethodMirror m : method.classMirror.getDirectMethods()){ // We skip members marked with @Ignore if(m.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(Util.strip(m.getName()).equals(lookupName)){ meth = m; break; } } if(meth == null || meth.getReturnType() == null){ method.setType(logModelResolutionError(method.getContainer(), "Error while resolving toplevel method "+method.getQualifiedNameString()+": static method missing")); return; } if(!meth.isStatic()){ method.setType(logModelResolutionError(method.getContainer(), "Error while resolving toplevel method "+method.getQualifiedNameString()+": method is not static")); return; } // save the method name method.setRealMethodName(meth.getName()); // save the method method.setMethodMirror(meth); // type params first setTypeParameters(method, meth); // now its parameters setParameters(method, meth, true /* toplevel methods are always Ceylon */, method); method.setType(obtainType(meth.getReturnType(), meth, method, Decl.getModuleContainer(method), VarianceLocation.COVARIANT, "toplevel method", method)); method.setDeclaredAnything(meth.isDeclaredVoid()); markUnboxed(method, meth.getReturnType()); markTypeErased(method, meth, meth.getReturnType()); method.setAnnotation(meth.getAnnotation(CEYLON_LANGUAGE_ANNOTATION_ANNOTATION) != null); setAnnotations(method, meth); setAnnotationConstructor(method, meth); }finally{ timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } private void setAnnotationConstructor(LazyMethod method, MethodMirror meth) { AnnotationInvocation ai = loadAnnotationInvocation(method, method.classMirror, meth); if (ai != null) { loadAnnotationConstructorDefaultedParameters(method, meth, ai); ai.setConstructorDeclaration(method); method.setAnnotationConstructor(ai); } } private AnnotationInvocation loadAnnotationInvocation( LazyMethod method, AnnotatedMirror annoInstMirror, MethodMirror meth) { AnnotationInvocation ai = null; AnnotationMirror annotationInvocationAnnotation = null; List<AnnotationMirror> annotationTree = getAnnotationArrayValue(annoInstMirror, CEYLON_ANNOTATION_INSTANTIATION_TREE_ANNOTATION, "value"); if (annotationTree != null && !annotationTree.isEmpty()) { annotationInvocationAnnotation = annotationTree.get(0); } else { annotationInvocationAnnotation = annoInstMirror.getAnnotation(CEYLON_ANNOTATION_INSTANTIATION_ANNOTATION); } //stringValueAnnotation = annoInstMirror.getAnnotation(CEYLON_STRING_VALUE_ANNOTATION); if (annotationInvocationAnnotation != null) { ai = new AnnotationInvocation(); setPrimaryFromAnnotationInvocationAnnotation(annotationInvocationAnnotation, ai); loadAnnotationInvocationArguments(new ArrayList(2), method, ai, annotationInvocationAnnotation, annotationTree, annoInstMirror); } return ai; } private void loadAnnotationInvocationArguments( List<AnnotationFieldName> path, LazyMethod method, AnnotationInvocation ai, AnnotationMirror annotationInvocationAnnotation, List<AnnotationMirror> annotationTree, AnnotatedMirror dpm) { List<Short> argumentCodes = (List<Short>)annotationInvocationAnnotation.getValue(CEYLON_ANNOTATION_INSTANTIATION_ARGUMENTS_MEMBER); if(argumentCodes != null){ for (int ii = 0; ii < argumentCodes.size(); ii++) { short code = argumentCodes.get(ii); AnnotationArgument argument = new AnnotationArgument(); Parameter classParameter = ai.getParameters().get(ii); argument.setParameter(classParameter); path.add(argument); argument.setTerm(loadAnnotationArgumentTerm(path, method, ai, classParameter, annotationTree, dpm, code)); path.remove(path.size()-1); ai.getAnnotationArguments().add(argument); } } } public AnnotationTerm decode(List<Parameter> sourceParameters, AnnotationInvocation info, Parameter parameter, AnnotatedMirror dpm, List<AnnotationFieldName> path, int code) { AnnotationTerm result; if (code == Short.MIN_VALUE) { return findLiteralAnnotationTerm(path, parameter, dpm); } else if (code < 0) { InvocationAnnotationTerm invocation = new InvocationAnnotationTerm(); result = invocation; } else if (code >= 0 && code < 512) { ParameterAnnotationTerm parameterArgument = new ParameterAnnotationTerm(); boolean spread = false; if (code >= 256) { spread = true; code-=256; } parameterArgument.setSpread(spread); Parameter sourceParameter = sourceParameters.get(code); parameterArgument.setSourceParameter(sourceParameter); //result.setTargetParameter(sourceParameter); result = parameterArgument; } else { throw new RuntimeException(); } return result; } private AnnotationTerm loadAnnotationArgumentTerm( List<AnnotationFieldName> path, LazyMethod method, AnnotationInvocation ai, Parameter parameter, List<AnnotationMirror> annotationTree, AnnotatedMirror dpm, short code) { if (code < 0 && code != Short.MIN_VALUE) { AnnotationMirror i = annotationTree.get(-code); AnnotationInvocation nested = new AnnotationInvocation(); setPrimaryFromAnnotationInvocationAnnotation(i, nested); loadAnnotationInvocationArguments(path, method, nested, i, annotationTree, dpm); InvocationAnnotationTerm term = new InvocationAnnotationTerm(); term.setInstantiation(nested); return term; } else { AnnotationTerm term = decode(method.getParameterLists().get(0).getParameters(), ai, parameter, dpm, path, code); return term; } } private void setPrimaryFromAnnotationInvocationAnnotation(AnnotationMirror annotationInvocationAnnotation, AnnotationInvocation ai) { TypeMirror annotationType = (TypeMirror)annotationInvocationAnnotation.getValue(CEYLON_ANNOTATION_INSTANTIATION_ANNOTATION_MEMBER); ClassMirror annotationClassMirror = annotationType.getDeclaredClass(); if (annotationClassMirror.getAnnotation(CEYLON_METHOD_ANNOTATION) != null) { ai.setPrimary((Method)convertToDeclaration(annotationClassMirror, DeclarationType.VALUE)); } else { ai.setPrimary((Class)convertToDeclaration(annotationClassMirror, DeclarationType.TYPE)); } } private void loadAnnotationConstructorDefaultedParameters( LazyMethod method, MethodMirror meth, AnnotationInvocation ai) { for (Parameter ctorParam : method.getParameterLists().get(0).getParameters()) { AnnotationConstructorParameter acp = new AnnotationConstructorParameter(); acp.setParameter(ctorParam); if (ctorParam.isDefaulted()) { acp.setDefaultArgument( loadAnnotationConstructorDefaultedParameter(method, meth, ctorParam, acp)); } ai.getConstructorParameters().add(acp); } } private AnnotationTerm loadAnnotationConstructorDefaultedParameter( LazyMethod method, MethodMirror meth, Parameter ctorParam, AnnotationConstructorParameter acp) { // Find the method mirror for the DPM for (MethodMirror mm : method.classMirror.getDirectMethods()) { if (mm.getName().equals(Naming.getDefaultedParamMethodName(method, ctorParam))) { // Create the appropriate AnnotationTerm if (mm.getAnnotation(CEYLON_ANNOTATION_INSTANTIATION_ANNOTATION) != null) { // If the DPM has a @AnnotationInstantiation // then it must be an invocation term so recurse InvocationAnnotationTerm invocationTerm = new InvocationAnnotationTerm(); invocationTerm.setInstantiation(loadAnnotationInvocation(method, mm, meth)); return invocationTerm; } else { return loadLiteralAnnotationTerm(ctorParam, mm); } } } return null; } /** * Loads a LiteralAnnotationTerm according to the presence of * <ul> * <li>{@code @StringValue} <li>{@code @IntegerValue} <li>etc * </ul> * @param ctorParam * */ private LiteralAnnotationTerm loadLiteralAnnotationTerm(Parameter parameter, AnnotatedMirror mm) { boolean singleValue = !typeFactory.isIterableType(parameter.getType()) || typeFactory.getStringDeclaration().equals(parameter.getType().getDeclaration()); AnnotationMirror valueAnnotation = mm.getAnnotation(CEYLON_STRING_VALUE_ANNOTATION); if (valueAnnotation != null) { return readStringValuesAnnotation(valueAnnotation, singleValue); } valueAnnotation = mm.getAnnotation(CEYLON_INTEGER_VALUE_ANNOTATION); if (valueAnnotation != null) { return readIntegerValuesAnnotation(valueAnnotation, singleValue); } valueAnnotation = mm.getAnnotation(CEYLON_BOOLEAN_VALUE_ANNOTATION); if (valueAnnotation != null) { return readBooleanValuesAnnotation(valueAnnotation, singleValue); } valueAnnotation = mm.getAnnotation(CEYLON_DECLARATION_VALUE_ANNOTATION); if (valueAnnotation != null) { return readDeclarationValuesAnnotation(valueAnnotation, singleValue); } valueAnnotation = mm.getAnnotation(CEYLON_OBJECT_VALUE_ANNOTATION); if (valueAnnotation != null) { return readObjectValuesAnnotation(valueAnnotation, singleValue); } valueAnnotation = mm.getAnnotation(CEYLON_CHARACTER_VALUE_ANNOTATION); if (valueAnnotation != null) { return readCharacterValuesAnnotation(valueAnnotation, singleValue); } valueAnnotation = mm.getAnnotation(CEYLON_FLOAT_VALUE_ANNOTATION); if (valueAnnotation != null) { return readFloatValuesAnnotation(valueAnnotation, singleValue); } return null; } /** * Searches the {@code @*Exprs} for one containing a {@code @*Value} * whose {@code name} matches the given namePath returning the first * match, or null. */ private LiteralAnnotationTerm findLiteralAnnotationTerm(List<AnnotationFieldName> namePath, Parameter parameter, AnnotatedMirror mm) { boolean singeValue = !typeFactory.isIterableType(parameter.getType()) || typeFactory.getStringDeclaration().equals(parameter.getType().getDeclaration()); final String name = Naming.getAnnotationFieldName(namePath); AnnotationMirror exprsAnnotation = mm.getAnnotation(CEYLON_STRING_EXPRS_ANNOTATION); if (exprsAnnotation != null) { for (AnnotationMirror valueAnnotation : getAnnotationAnnoValues(exprsAnnotation, "value")) { String path = (String)valueAnnotation.getValue("name"); if (name.equals(path)) { return readStringValuesAnnotation(valueAnnotation, singeValue); } } } exprsAnnotation = mm.getAnnotation(CEYLON_INTEGER_EXPRS_ANNOTATION); if (exprsAnnotation != null) { for (AnnotationMirror valueAnnotation : getAnnotationAnnoValues(exprsAnnotation, "value")) { String path = (String)valueAnnotation.getValue("name"); if (name.equals(path)) { return readIntegerValuesAnnotation(valueAnnotation, singeValue); } } } exprsAnnotation = mm.getAnnotation(CEYLON_BOOLEAN_EXPRS_ANNOTATION); if (exprsAnnotation != null) { for (AnnotationMirror valueAnnotation : getAnnotationAnnoValues(exprsAnnotation, "value")) { String path = (String)valueAnnotation.getValue("name"); if (name.equals(path)) { return readBooleanValuesAnnotation(valueAnnotation, singeValue); } } } exprsAnnotation = mm.getAnnotation(CEYLON_DECLARATION_EXPRS_ANNOTATION); if (exprsAnnotation != null) { for (AnnotationMirror valueAnnotation : getAnnotationAnnoValues(exprsAnnotation, "value")) { String path = (String)valueAnnotation.getValue("name"); if (name.equals(path)) { return readDeclarationValuesAnnotation(valueAnnotation, singeValue); } } } exprsAnnotation = mm.getAnnotation(CEYLON_OBJECT_EXPRS_ANNOTATION); if (exprsAnnotation != null) { for (AnnotationMirror valueAnnotation : getAnnotationAnnoValues(exprsAnnotation, "value")) { String path = (String)valueAnnotation.getValue("name"); if (name.equals(path)) { return readObjectValuesAnnotation(valueAnnotation, singeValue); } } } exprsAnnotation = mm.getAnnotation(CEYLON_CHARACTER_EXPRS_ANNOTATION); if (exprsAnnotation != null) { for (AnnotationMirror valueAnnotation : getAnnotationAnnoValues(exprsAnnotation, "value")) { String path = (String)valueAnnotation.getValue("name"); if (name.equals(path)) { return readCharacterValuesAnnotation(valueAnnotation, singeValue); } } } exprsAnnotation = mm.getAnnotation(CEYLON_FLOAT_EXPRS_ANNOTATION); if (exprsAnnotation != null) { for (AnnotationMirror valueAnnotation : getAnnotationAnnoValues(exprsAnnotation, "value")) { String path = (String)valueAnnotation.getValue("name"); if (name.equals(path)) { return readFloatValuesAnnotation(valueAnnotation, singeValue); } } } return null; } private LiteralAnnotationTerm readObjectValuesAnnotation( AnnotationMirror valueAnnotation, boolean singleValue) { if (singleValue) { TypeMirror klass = getAnnotationClassValues(valueAnnotation, "value").get(0); ProducedType type = obtainType(klass, null, null, null); ObjectLiteralAnnotationTerm term = new ObjectLiteralAnnotationTerm(type); return term; } else { CollectionLiteralAnnotationTerm result = new CollectionLiteralAnnotationTerm(ObjectLiteralAnnotationTerm.FACTORY); for (TypeMirror klass : getAnnotationClassValues(valueAnnotation, "value")) { ProducedType type = obtainType(klass, null, null, null); result.addElement(new ObjectLiteralAnnotationTerm(type)); } return result; } } private LiteralAnnotationTerm readStringValuesAnnotation( AnnotationMirror valueAnnotation, boolean singleValue) { if (singleValue) { String value = getAnnotationStringValues(valueAnnotation, "value").get(0); StringLiteralAnnotationTerm term = new StringLiteralAnnotationTerm(value); return term; } else { CollectionLiteralAnnotationTerm result = new CollectionLiteralAnnotationTerm(StringLiteralAnnotationTerm.FACTORY); for (String value : getAnnotationStringValues(valueAnnotation, "value")) { result.addElement(new StringLiteralAnnotationTerm(value)); } return result; } } private LiteralAnnotationTerm readIntegerValuesAnnotation( AnnotationMirror valueAnnotation, boolean singleValue) { if (singleValue) { Long value = getAnnotationLongValues(valueAnnotation, "value").get(0); IntegerLiteralAnnotationTerm term = new IntegerLiteralAnnotationTerm(value); return term; } else { CollectionLiteralAnnotationTerm result = new CollectionLiteralAnnotationTerm(IntegerLiteralAnnotationTerm.FACTORY); for (Long value : getAnnotationLongValues(valueAnnotation, "value")) { result.addElement(new IntegerLiteralAnnotationTerm(value)); } return result; } } private LiteralAnnotationTerm readCharacterValuesAnnotation( AnnotationMirror valueAnnotation, boolean singleValue) { if (singleValue) { Integer value = getAnnotationIntegerValues(valueAnnotation, "value").get(0); CharacterLiteralAnnotationTerm term = new CharacterLiteralAnnotationTerm(value); return term; } else { CollectionLiteralAnnotationTerm result = new CollectionLiteralAnnotationTerm(CharacterLiteralAnnotationTerm.FACTORY); for (Integer value : getAnnotationIntegerValues(valueAnnotation, "value")) { result.addElement(new CharacterLiteralAnnotationTerm(value)); } return result; } } private LiteralAnnotationTerm readFloatValuesAnnotation( AnnotationMirror valueAnnotation, boolean singleValue) { if (singleValue) { Double value = getAnnotationDoubleValues(valueAnnotation, "value").get(0); FloatLiteralAnnotationTerm term = new FloatLiteralAnnotationTerm(value); return term; } else { CollectionLiteralAnnotationTerm result = new CollectionLiteralAnnotationTerm(FloatLiteralAnnotationTerm.FACTORY); for (Double value : getAnnotationDoubleValues(valueAnnotation, "value")) { result.addElement(new FloatLiteralAnnotationTerm(value)); } return result; } } private LiteralAnnotationTerm readBooleanValuesAnnotation( AnnotationMirror valueAnnotation, boolean singleValue) { if (singleValue) { boolean value = getAnnotationBooleanValues(valueAnnotation, "value").get(0); BooleanLiteralAnnotationTerm term = new BooleanLiteralAnnotationTerm(value); return term; } else { CollectionLiteralAnnotationTerm result = new CollectionLiteralAnnotationTerm(BooleanLiteralAnnotationTerm.FACTORY); for (Boolean value : getAnnotationBooleanValues(valueAnnotation, "value")) { result.addElement(new BooleanLiteralAnnotationTerm(value)); } return result; } } private LiteralAnnotationTerm readDeclarationValuesAnnotation( AnnotationMirror valueAnnotation, boolean singleValue) { if (singleValue) { String value = getAnnotationStringValues(valueAnnotation, "value").get(0); DeclarationLiteralAnnotationTerm term = new DeclarationLiteralAnnotationTerm(value); return term; } else { CollectionLiteralAnnotationTerm result = new CollectionLiteralAnnotationTerm(DeclarationLiteralAnnotationTerm.FACTORY); for (String value : getAnnotationStringValues(valueAnnotation, "value")) { result.addElement(new DeclarationLiteralAnnotationTerm(value)); } return result; } } // // Satisfied Types private List<String> getSatisfiedTypesFromAnnotations(AnnotatedMirror symbol) { return getAnnotationArrayValue(symbol, CEYLON_SATISFIED_TYPES_ANNOTATION); } private void setSatisfiedTypes(ClassOrInterface klass, ClassMirror classMirror) { List<String> satisfiedTypes = getSatisfiedTypesFromAnnotations(classMirror); if(satisfiedTypes != null){ klass.getSatisfiedTypes().addAll(getTypesList(satisfiedTypes, klass, Decl.getModuleContainer(klass), "satisfied types", klass.getQualifiedNameString())); }else{ for(TypeMirror iface : classMirror.getInterfaces()){ // ignore ReifiedType interfaces if(sameType(iface, CEYLON_REIFIED_TYPE_TYPE)) continue; try{ klass.getSatisfiedTypes().add(getNonPrimitiveType(iface, klass, VarianceLocation.INVARIANT)); }catch(ModelResolutionException x){ PackageMirror classPackage = classMirror.getPackage(); if(JDKUtils.isJDKAnyPackage(classPackage.getQualifiedName())){ if(iface.getKind() == TypeKind.DECLARED){ // check if it's a JDK thing ClassMirror ifaceClass = iface.getDeclaredClass(); PackageMirror ifacePackage = ifaceClass.getPackage(); if(JDKUtils.isOracleJDKAnyPackage(ifacePackage.getQualifiedName())){ // just log and ignore it logMissingOracleType(iface.getQualifiedName()); continue; } } } } } } } // // Case Types private List<String> getCaseTypesFromAnnotations(AnnotatedMirror symbol) { return getAnnotationArrayValue(symbol, CEYLON_CASE_TYPES_ANNOTATION); } private String getSelfTypeFromAnnotations(AnnotatedMirror symbol) { return getAnnotationStringValue(symbol, CEYLON_CASE_TYPES_ANNOTATION, "of"); } private void setCaseTypes(ClassOrInterface klass, ClassMirror classMirror) { String selfType = getSelfTypeFromAnnotations(classMirror); Module moduleScope = Decl.getModuleContainer(klass); if(selfType != null && !selfType.isEmpty()){ ProducedType type = decodeType(selfType, klass, moduleScope, "self type"); if(!(type.getDeclaration() instanceof TypeParameter)){ logError("Invalid type signature for self type of "+klass.getQualifiedNameString()+": "+selfType+" is not a type parameter"); }else{ klass.setSelfType(type); List<ProducedType> caseTypes = new LinkedList<ProducedType>(); caseTypes.add(type); klass.setCaseTypes(caseTypes); } } else { List<String> caseTypes = getCaseTypesFromAnnotations(classMirror); if(caseTypes != null && !caseTypes.isEmpty()){ klass.setCaseTypes(getTypesList(caseTypes, klass, moduleScope, "case types", klass.getQualifiedNameString())); } } } private List<ProducedType> getTypesList(List<String> caseTypes, Scope scope, Module moduleScope, String targetType, String targetName) { List<ProducedType> producedTypes = new LinkedList<ProducedType>(); for(String type : caseTypes){ producedTypes.add(decodeType(type, scope, moduleScope, targetType)); } return producedTypes; } // // Type parameters loading @SuppressWarnings("unchecked") private List<AnnotationMirror> getTypeParametersFromAnnotations(AnnotatedMirror symbol) { return (List<AnnotationMirror>) getAnnotationValue(symbol, CEYLON_TYPE_PARAMETERS); } // from our annotation @SuppressWarnings("deprecation") private void setTypeParametersFromAnnotations(Scope scope, List<TypeParameter> params, AnnotatedMirror mirror, List<AnnotationMirror> typeParameterAnnotations, List<TypeParameterMirror> typeParameterMirrors) { // We must first add every type param, before we resolve the bounds, which can // refer to type params. String selfTypeName = getSelfTypeFromAnnotations(mirror); int i=0; for(AnnotationMirror typeParamAnnotation : typeParameterAnnotations){ TypeParameter param = new TypeParameter(); param.setUnit(((Element)scope).getUnit()); param.setContainer(scope); param.setDeclaration((Declaration) scope); // let's not trigger the lazy-loading if we're completing a LazyClass/LazyInterface if(scope instanceof LazyContainer) ((LazyContainer)scope).addMember(param); else // must be a method scope.getMembers().add(param); param.setName((String)typeParamAnnotation.getValue("value")); param.setExtendedType(typeFactory.getAnythingDeclaration().getType()); if(i < typeParameterMirrors.size()){ TypeParameterMirror typeParameterMirror = typeParameterMirrors.get(i); param.setNonErasedBounds(hasNonErasedBounds(typeParameterMirror)); } String varianceName = (String) typeParamAnnotation.getValue("variance"); if(varianceName != null){ if(varianceName.equals("IN")){ param.setContravariant(true); }else if(varianceName.equals("OUT")) param.setCovariant(true); } // If this is a self type param then link it to its type's declaration if (param.getName().equals(selfTypeName)) { param.setSelfTypedDeclaration((TypeDeclaration)scope); } params.add(param); i++; } Module moduleScope = Decl.getModuleContainer(scope); // Now all type params have been set, we can resolve the references parts Iterator<TypeParameter> paramsIterator = params.iterator(); for(AnnotationMirror typeParamAnnotation : typeParameterAnnotations){ TypeParameter param = paramsIterator.next(); @SuppressWarnings("unchecked") List<String> satisfiesAttribute = (List<String>)typeParamAnnotation.getValue("satisfies"); setListOfTypes(param.getSatisfiedTypes(), satisfiesAttribute, scope, moduleScope, "type parameter '"+param.getName()+"' satisfied types"); @SuppressWarnings("unchecked") List<String> caseTypesAttribute = (List<String>)typeParamAnnotation.getValue("caseTypes"); if(caseTypesAttribute != null && !caseTypesAttribute.isEmpty()) param.setCaseTypes(new LinkedList<ProducedType>()); setListOfTypes(param.getCaseTypes(), caseTypesAttribute, scope, moduleScope, "type parameter '"+param.getName()+"' case types"); @SuppressWarnings("unchecked") String defaultValueAttribute = (String)typeParamAnnotation.getValue("defaultValue"); if(defaultValueAttribute != null && !defaultValueAttribute.isEmpty()){ ProducedType decodedType = decodeType(defaultValueAttribute, scope, moduleScope, "type parameter '"+param.getName()+"' defaultValue"); param.setDefaultTypeArgument(decodedType); param.setDefaulted(true); } } } private boolean hasNonErasedBounds(TypeParameterMirror typeParameterMirror) { List<TypeMirror> bounds = typeParameterMirror.getBounds(); // if we have at least one bound and not a single Object one return bounds.size() > 0 && (bounds.size() != 1 || !sameType(bounds.get(0), OBJECT_TYPE)); } private void setListOfTypes(List<ProducedType> destinationTypeList, List<String> serialisedTypes, Scope scope, Module moduleScope, String targetType) { if(serialisedTypes != null){ for (String serialisedType : serialisedTypes) { ProducedType decodedType = decodeType(serialisedType, scope, moduleScope, targetType); destinationTypeList.add(decodedType); } } } // from java type info @SuppressWarnings("deprecation") private void setTypeParameters(Scope scope, List<TypeParameter> params, List<TypeParameterMirror> typeParameters) { // We must first add every type param, before we resolve the bounds, which can // refer to type params. for(TypeParameterMirror typeParam : typeParameters){ TypeParameter param = new TypeParameter(); param.setUnit(((Element)scope).getUnit()); param.setContainer(scope); param.setDeclaration((Declaration) scope); // let's not trigger the lazy-loading if we're completing a LazyClass/LazyInterface if(scope instanceof LazyContainer) ((LazyContainer)scope).addMember(param); else // must be a method scope.getMembers().add(param); param.setName(typeParam.getName()); param.setExtendedType(typeFactory.getAnythingDeclaration().getType()); params.add(param); } // Now all type params have been set, we can resolve the references parts Iterator<TypeParameter> paramsIterator = params.iterator(); for(TypeParameterMirror typeParam : typeParameters){ TypeParameter param = paramsIterator.next(); List<TypeMirror> bounds = typeParam.getBounds(); for(TypeMirror bound : bounds){ ProducedType boundType; // we turn java's default upper bound java.lang.Object into ceylon.language.Object if(sameType(bound, OBJECT_TYPE)){ // avoid adding java's default upper bound if it's just there with no meaning if(bounds.size() == 1) break; boundType = getNonPrimitiveType(CEYLON_OBJECT_TYPE, scope, VarianceLocation.INVARIANT); }else boundType = getNonPrimitiveType(bound, scope, VarianceLocation.INVARIANT); param.getSatisfiedTypes().add(boundType); } } } // method private void setTypeParameters(Method method, MethodMirror methodMirror) { List<TypeParameter> params = new LinkedList<TypeParameter>(); method.setTypeParameters(params); List<AnnotationMirror> typeParameters = getTypeParametersFromAnnotations(methodMirror); if(typeParameters != null) { setTypeParametersFromAnnotations(method, params, methodMirror, typeParameters, methodMirror.getTypeParameters()); } else { setTypeParameters(method, params, methodMirror.getTypeParameters()); } } // class private void setTypeParameters(TypeDeclaration klass, ClassMirror classMirror) { List<TypeParameter> params = new LinkedList<TypeParameter>(); klass.setTypeParameters(params); List<AnnotationMirror> typeParameters = getTypeParametersFromAnnotations(classMirror); if(typeParameters != null) { setTypeParametersFromAnnotations(klass, params, classMirror, typeParameters, classMirror.getTypeParameters()); } else { setTypeParameters(klass, params, classMirror.getTypeParameters()); } } // // TypeParsing and ModelLoader private ProducedType decodeType(String value, Scope scope, Module moduleScope, String targetType) { return decodeType(value, scope, moduleScope, targetType, null); } private ProducedType decodeType(String value, Scope scope, Module moduleScope, String targetType, Declaration target) { try{ return typeParser.decodeType(value, scope, moduleScope); }catch(TypeParserException x){ String text = formatTypeErrorMessage("Error while parsing type of", targetType, target, scope); return logModelResolutionException(x.getMessage(), scope, text); }catch(ModelResolutionException x){ String text = formatTypeErrorMessage("Error while resolving type of", targetType, target, scope); return logModelResolutionException(x, scope, text); } } private String formatTypeErrorMessage(String prefix, String targetType, Declaration target, Scope scope) { String forTarget; if(target != null) forTarget = " for "+target.getQualifiedNameString(); else if(scope != null) forTarget = " for "+scope.getQualifiedNameString(); else forTarget = ""; return prefix+" "+targetType+forTarget; } /** Warning: only valid for toplevel types, not for type parameters */ private ProducedType obtainType(TypeMirror type, AnnotatedMirror symbol, Scope scope, Module moduleScope, VarianceLocation variance, String targetType, Declaration target) { String typeName = getAnnotationStringValue(symbol, CEYLON_TYPE_INFO_ANNOTATION); if (typeName != null) { ProducedType ret = decodeType(typeName, scope, moduleScope, targetType, target); // even decoded types need to fit with the reality of the underlying type ret.setUnderlyingType(getUnderlyingType(type, TypeLocation.TOPLEVEL)); return ret; } else { try{ return obtainType(type, scope, TypeLocation.TOPLEVEL, variance); }catch(ModelResolutionException x){ String text = formatTypeErrorMessage("Error while resolving type of", targetType, target, scope); return logModelResolutionException(x, scope, text); } } } private enum TypeLocation { TOPLEVEL, TYPE_PARAM; } private enum VarianceLocation { /** * Used in parameter */ CONTRAVARIANT, /** * Used in method return value */ COVARIANT, /** * For field */ INVARIANT; } private String getUnderlyingType(TypeMirror type, TypeLocation location){ // don't erase to c.l.String if in a type param location if ((sameType(type, STRING_TYPE) && location != TypeLocation.TYPE_PARAM) || sameType(type, PRIM_BYTE_TYPE) || sameType(type, PRIM_SHORT_TYPE) || sameType(type, PRIM_INT_TYPE) || sameType(type, PRIM_FLOAT_TYPE) || sameType(type, PRIM_CHAR_TYPE)) { return type.getQualifiedName(); } return null; } private ProducedType obtainType(TypeMirror type, Scope scope, TypeLocation location, VarianceLocation variance) { TypeMirror originalType = type; // ERASURE type = applyTypeMapping(type, location); ProducedType ret = getNonPrimitiveType(type, scope, variance); if (ret.getUnderlyingType() == null) { ret.setUnderlyingType(getUnderlyingType(originalType, location)); } return ret; } private TypeMirror applyTypeMapping(TypeMirror type, TypeLocation location) { // don't erase to c.l.String if in a type param location if (sameType(type, STRING_TYPE) && location != TypeLocation.TYPE_PARAM) { return CEYLON_STRING_TYPE; } else if (sameType(type, PRIM_BOOLEAN_TYPE)) { return CEYLON_BOOLEAN_TYPE; } else if (sameType(type, PRIM_BYTE_TYPE)) { return CEYLON_INTEGER_TYPE; } else if (sameType(type, PRIM_SHORT_TYPE)) { return CEYLON_INTEGER_TYPE; } else if (sameType(type, PRIM_INT_TYPE)) { return CEYLON_INTEGER_TYPE; } else if (sameType(type, PRIM_LONG_TYPE)) { return CEYLON_INTEGER_TYPE; } else if (sameType(type, PRIM_FLOAT_TYPE)) { return CEYLON_FLOAT_TYPE; } else if (sameType(type, PRIM_DOUBLE_TYPE)) { return CEYLON_FLOAT_TYPE; } else if (sameType(type, PRIM_CHAR_TYPE)) { return CEYLON_CHARACTER_TYPE; } else if (sameType(type, OBJECT_TYPE)) { return CEYLON_OBJECT_TYPE; } else if (type.getKind() == TypeKind.ARRAY) { TypeMirror ct = type.getComponentType(); if (sameType(ct, PRIM_BOOLEAN_TYPE)) { return JAVA_BOOLEAN_ARRAY_TYPE; } else if (sameType(ct, PRIM_BYTE_TYPE)) { return JAVA_BYTE_ARRAY_TYPE; } else if (sameType(ct, PRIM_SHORT_TYPE)) { return JAVA_SHORT_ARRAY_TYPE; } else if (sameType(ct, PRIM_INT_TYPE)) { return JAVA_INT_ARRAY_TYPE; } else if (sameType(ct, PRIM_LONG_TYPE)) { return JAVA_LONG_ARRAY_TYPE; } else if (sameType(ct, PRIM_FLOAT_TYPE)) { return JAVA_FLOAT_ARRAY_TYPE; } else if (sameType(ct, PRIM_DOUBLE_TYPE)) { return JAVA_DOUBLE_ARRAY_TYPE; } else if (sameType(ct, PRIM_CHAR_TYPE)) { return JAVA_CHAR_ARRAY_TYPE; } else { // object array return new SimpleReflType(JAVA_LANG_OBJECT_ARRAY, SimpleReflType.Module.JDK, TypeKind.DECLARED, ct); } } return type; } private boolean sameType(TypeMirror t1, TypeMirror t2) { // make sure we deal with arrays which can't have a qualified name if(t1.getKind() == TypeKind.ARRAY){ if(t2.getKind() != TypeKind.ARRAY) return false; return sameType(t1.getComponentType(), t2.getComponentType()); } if(t2.getKind() == TypeKind.ARRAY) return false; // the rest should be OK return t1.getQualifiedName().equals(t2.getQualifiedName()); } @Override public Declaration getDeclaration(Module module, String typeName, DeclarationType declarationType) { return convertToDeclaration(module, typeName, declarationType); } private ProducedType getNonPrimitiveType(TypeMirror type, Scope scope, VarianceLocation variance) { TypeDeclaration declaration = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(type, scope, DeclarationType.TYPE); if(declaration == null){ throw new ModelResolutionException("Failed to find declaration for "+type); } return applyTypeArguments(declaration, type, scope, variance, TypeMappingMode.NORMAL, null); } private enum TypeMappingMode { NORMAL, GENERATOR } @SuppressWarnings("serial") private static class RecursiveTypeParameterBoundException extends RuntimeException {} private ProducedType applyTypeArguments(TypeDeclaration declaration, TypeMirror type, Scope scope, VarianceLocation variance, TypeMappingMode mode, Set<TypeDeclaration> rawDeclarationsSeen) { List<TypeMirror> javacTypeArguments = type.getTypeArguments(); if(!javacTypeArguments.isEmpty()){ // detect recursive bounds that we can't possibly satisfy, such as Foo<T extends Foo<T>> if(rawDeclarationsSeen != null && !rawDeclarationsSeen.add(declaration)) throw new RecursiveTypeParameterBoundException(); try{ List<ProducedType> typeArguments = new ArrayList<ProducedType>(javacTypeArguments.size()); for(TypeMirror typeArgument : javacTypeArguments){ // if a single type argument is a wildcard and we are in a covariant location, we erase to Object if(typeArgument.getKind() == TypeKind.WILDCARD){ // if contravariant or if it's a ceylon type we use its bound if(variance == VarianceLocation.CONTRAVARIANT || Decl.isCeylon(declaration)){ TypeMirror bound = typeArgument.getUpperBound(); if(bound == null) bound = typeArgument.getLowerBound(); // if it has no bound let's take Object if(bound == null){ // add the type arg and move to the next one typeArguments.add(typeFactory.getObjectDeclaration().getType()); continue; } typeArgument = bound; } else { ProducedType result = typeFactory.getObjectDeclaration().getType(); result.setUnderlyingType(type.getQualifiedName()); return result; } } ProducedType producedTypeArgument; if(mode == TypeMappingMode.NORMAL) producedTypeArgument = obtainType(typeArgument, scope, TypeLocation.TYPE_PARAM, variance); else producedTypeArgument = obtainTypeParameterBound(typeArgument, scope, rawDeclarationsSeen); typeArguments.add(producedTypeArgument); } return declaration.getProducedType(getQualifyingType(declaration), typeArguments); }finally{ if(rawDeclarationsSeen != null) rawDeclarationsSeen.remove(declaration); } }else if(!declaration.getTypeParameters().isEmpty()){ // we have a raw type ProducedType result; if(variance == VarianceLocation.CONTRAVARIANT || Decl.isCeylon(declaration)){ // detect recursive bounds that we can't possibly satisfy, such as Foo<T extends Foo<T>> if(rawDeclarationsSeen == null) rawDeclarationsSeen = new HashSet<TypeDeclaration>(); if(!rawDeclarationsSeen.add(declaration)) throw new RecursiveTypeParameterBoundException(); try{ // generate a compatible bound for each type parameter int count = declaration.getTypeParameters().size(); List<ProducedType> typeArguments = new ArrayList<ProducedType>(count); for(TypeParameterMirror tp : type.getDeclaredClass().getTypeParameters()){ // FIXME: multiple bounds? if(tp.getBounds().size() == 1){ TypeMirror bound = tp.getBounds().get(0); typeArguments.add(obtainTypeParameterBound(bound, declaration, rawDeclarationsSeen)); }else typeArguments.add(typeFactory.getObjectDeclaration().getType()); } result = declaration.getProducedType(getQualifyingType(declaration), typeArguments); }catch(RecursiveTypeParameterBoundException x){ // damnit, go for Object result = typeFactory.getObjectDeclaration().getType(); }finally{ rawDeclarationsSeen.remove(declaration); } }else{ // covariant raw erases to Object result = typeFactory.getObjectDeclaration().getType(); } result.setUnderlyingType(type.getQualifiedName()); result.setRaw(true); return result; } return declaration.getType(); } private ProducedType obtainTypeParameterBound(TypeMirror type, Scope scope, Set<TypeDeclaration> rawDeclarationsSeen) { // type variables are never mapped if(type.getKind() == TypeKind.TYPEVAR){ TypeParameterMirror typeParameter = type.getTypeParameter(); if(!typeParameter.getBounds().isEmpty()){ IntersectionType it = new IntersectionType(typeFactory); for(TypeMirror bound : typeParameter.getBounds()){ ProducedType boundModel = obtainTypeParameterBound(bound, scope, rawDeclarationsSeen); it.getSatisfiedTypes().add(boundModel); } return it.getType(); }else // no bound is Object return typeFactory.getObjectDeclaration().getType(); }else{ TypeMirror mappedType = applyTypeMapping(type, TypeLocation.TYPE_PARAM); TypeDeclaration declaration = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(mappedType, scope, DeclarationType.TYPE); if(declaration == null){ throw new RuntimeException("Failed to find declaration for "+type); } ProducedType ret = applyTypeArguments(declaration, type, scope, VarianceLocation.CONTRAVARIANT, TypeMappingMode.GENERATOR, rawDeclarationsSeen); if (ret.getUnderlyingType() == null) { ret.setUnderlyingType(getUnderlyingType(type, TypeLocation.TYPE_PARAM)); } return ret; } } private ProducedType getQualifyingType(TypeDeclaration declaration) { // As taken from ProducedType.getType(): if (declaration.isMember()) { return((ClassOrInterface) declaration.getContainer()).getType(); } return null; } @Override public synchronized ProducedType getType(Module module, String pkgName, String name, Scope scope) { if(scope != null){ TypeParameter typeParameter = lookupTypeParameter(scope, name); if(typeParameter != null) return typeParameter.getType(); } if(!isBootstrap || !name.startsWith(CEYLON_LANGUAGE)) { if(scope != null && pkgName != null){ Package containingPackage = Decl.getPackageContainer(scope); Package pkg = containingPackage.getModule().getPackage(pkgName); String relativeName = null; String unquotedName = name.replace("$", ""); if(!pkgName.isEmpty()){ if(unquotedName.startsWith(pkgName+".")) relativeName = unquotedName.substring(pkgName.length()+1); // else we don't try it's not in this package }else relativeName = unquotedName; if(relativeName != null && pkg != null){ Declaration declaration = pkg.getDirectMember(relativeName, null, false); // if we get a value, we want its type if(Decl.isValue(declaration) && ((Value)declaration).getTypeDeclaration().getName().equals(relativeName)) declaration = ((Value)declaration).getTypeDeclaration(); if(declaration instanceof TypeDeclaration) return ((TypeDeclaration)declaration).getType(); // if we have something but it's not a type decl, it's a: // - value that's not an object (why would we get its type here?) // - method (doesn't have a type of the same name) if(declaration != null) return null; } } Declaration declaration = convertToDeclaration(module, name, DeclarationType.TYPE); if(declaration instanceof TypeDeclaration) return ((TypeDeclaration)declaration).getType(); // we're looking for type declarations, so anything else doesn't work for us return null; } return findLanguageModuleDeclarationForBootstrap(name); } private ProducedType findLanguageModuleDeclarationForBootstrap(String name) { // make sure we don't return anything for ceylon.language if(name.equals(CEYLON_LANGUAGE)) return null; // we're bootstrapping ceylon.language so we need to return the ProducedTypes straight from the model we're compiling Module languageModule = modules.getLanguageModule(); int lastDot = name.lastIndexOf("."); if(lastDot == -1) return null; String pkgName = name.substring(0, lastDot); String simpleName = name.substring(lastDot+1); // Nothing is a special case with no real decl if(name.equals("ceylon.language.Nothing")) return typeFactory.getNothingDeclaration().getType(); // find the right package Package pkg = languageModule.getDirectPackage(pkgName); if(pkg != null){ Declaration member = pkg.getDirectMember(simpleName, null, false); // if we get a value, we want its type if(Decl.isValue(member) && ((Value)member).getTypeDeclaration().getName().equals(simpleName)){ member = ((Value)member).getTypeDeclaration(); } if(member instanceof TypeDeclaration) return ((TypeDeclaration)member).getType(); } throw new ModelResolutionException("Failed to look up given type in language module while bootstrapping: "+name); } public synchronized void removeDeclarations(List<Declaration> declarations) { List<String> keysToRemove = new ArrayList<String>(); // keep in sync with getOrCreateDeclaration for (Declaration decl : declarations) { String prefix = null, otherPrefix = null; String fqn = decl.getQualifiedNameString().replace("::", "."); Module module = Decl.getModuleContainer(decl.getContainer()); if(Decl.isToplevel(decl)){ if(Decl.isValue(decl)){ prefix = "V"; if(((Value)decl).getTypeDeclaration().isAnonymous()) otherPrefix = "C"; }else if(Decl.isMethod(decl)) prefix = "V"; } if(decl instanceof ClassOrInterface){ prefix = "C"; } // ignore declarations which we do not cache, like member method/attributes if(prefix != null){ declarationsByName.remove(cacheKeyByModule(module, prefix + fqn)); if(otherPrefix != null) declarationsByName.remove(cacheKeyByModule(module, otherPrefix + fqn)); } } for (Declaration decl : declarations) { if (decl instanceof LazyClass || decl instanceof LazyInterface) { Module module = Decl.getModuleContainer(decl.getContainer()); classMirrorCache.remove(cacheKeyByModule(module, decl.getQualifiedNameString().replace("::", "."))); } } } public synchronized void printStats(){ int loaded = 0; class Stats { int loaded, total; } Map<Package, Stats> loadedByPackage = new HashMap<Package, Stats>(); for(Declaration decl : declarationsByName.values()){ if(decl instanceof LazyElement){ Package pkg = getPackage(decl); if(pkg == null){ logVerbose("[Model loader stats: declaration "+decl.getName()+" has no package. Skipping.]"); continue; } Stats stats = loadedByPackage.get(pkg); if(stats == null){ stats = new Stats(); loadedByPackage.put(pkg, stats); } stats.total++; if(((LazyElement)decl).isLoaded()){ loaded++; stats.loaded++; } } } logVerbose("[Model loader: "+loaded+"(loaded)/"+declarationsByName.size()+"(total) declarations]"); for(Entry<Package, Stats> packageEntry : loadedByPackage.entrySet()){ logVerbose("[ Package "+packageEntry.getKey().getNameAsString()+": " +packageEntry.getValue().loaded+"(loaded)/"+packageEntry.getValue().total+"(total) declarations]"); } } private static Package getPackage(Object decl) { if(decl == null) return null; if(decl instanceof Package) return (Package) decl; return getPackage(((Declaration)decl).getContainer()); } protected void logMissingOracleType(String type) { logVerbose("Hopefully harmless completion failure in model loader: "+type +". This is most likely when the JDK depends on Oracle private classes that we can't find." +" As a result some model information will be incomplete."); } public void setupSourceFileObjects(List<?> treeHolders) { } public static boolean isJDKModule(String name) { return JDKUtils.isJDKModule(name) || JDKUtils.isOracleJDKModule(name); } @Override public Module getLoadedModule(String moduleName) { // FIXME: version? for(Module mod : modules.getListOfModules()){ if(mod.getNameAsString().equals(moduleName)) return mod; } return null; } public Module getLanguageModule() { return modules.getLanguageModule(); } public Module findModule(String name, String version){ if(name.equals(Module.DEFAULT_MODULE_NAME)) return modules.getDefaultModule(); for(Module module : modules.getListOfModules()){ if(module.getNameAsString().equals(name) && (version == null || module.getVersion() == null || version.equals(module.getVersion()))) return module; } return null; } public Module getJDKBaseModule() { return findModule(JAVA_BASE_MODULE_NAME, JDK_MODULE_VERSION); } protected abstract Module findModuleForClassMirror(ClassMirror classMirror); protected boolean isTypeHidden(Module module, String qualifiedName){ return module.getNameAsString().equals(JAVA_BASE_MODULE_NAME) && qualifiedName.equals("java.lang.Object"); } public synchronized Package findPackage(String quotedPkgName) { String pkgName = quotedPkgName.replace("$", ""); // in theory we only have one package with the same name per module in javac for(Package pkg : packagesByName.values()){ if(pkg.getNameAsString().equals(pkgName)) return pkg; } return null; } /** * See explanation in cacheModulelessPackages() below. This is called by LanguageCompiler during loadCompiledModules(). */ public synchronized LazyPackage findOrCreateModulelessPackage(String pkgName) { LazyPackage pkg = modulelessPackages.get(pkgName); if(pkg != null) return pkg; pkg = new LazyPackage(this); // FIXME: some refactoring needed pkg.setName(pkgName == null ? Collections.<String>emptyList() : Arrays.asList(pkgName.split("\\."))); modulelessPackages.put(pkgName, pkg); return pkg; } /** * Stef: this sucks balls, but the typechecker wants Packages created before we have any Module set up, including for parsing a module * file, and because the model loader looks up packages and caches them using their modules, we can't really have packages before we * have modules. Rather than rewrite the typechecker, we create moduleless packages during parsing, which means they are not cached with * their modules, and after the loadCompiledModules step above, we fix the package modules. Remains to be done is to move the packages * created from their cache to the right per-module cache. */ public synchronized void cacheModulelessPackages(){ for(LazyPackage pkg : modulelessPackages.values()){ String quotedPkgName = Util.quoteJavaKeywords(pkg.getQualifiedNameString()); packagesByName.put(cacheKeyByModule(pkg.getModule(), quotedPkgName), pkg); } modulelessPackages.clear(); } /** * Stef: after a lot of attempting, I failed to make the CompilerModuleManager produce a LazyPackage when the ModuleManager.initCoreModules * is called for the default package. Because it is called by the PhasedUnits constructor, which is called by the ModelLoader constructor, * which means the model loader is not yet in the context, so the CompilerModuleManager can't obtain it to pass it to the LazyPackage * constructor. A rewrite of the logic of the typechecker scanning would fix this, but at this point it's just faster to let it create * the wrong default package and fix it before we start parsing anything. */ public synchronized void fixDefaultPackage() { Module defaultModule = modules.getDefaultModule(); Package defaultPackage = defaultModule.getDirectPackage(""); if(defaultPackage instanceof LazyPackage == false){ LazyPackage newPkg = findOrCreateModulelessPackage(""); List<Package> defaultModulePackages = defaultModule.getPackages(); if(defaultModulePackages.size() != 1) throw new RuntimeException("Assertion failed: default module has more than the default package: "+defaultModulePackages.size()); defaultModulePackages.clear(); defaultModulePackages.add(newPkg); newPkg.setModule(defaultModule); defaultPackage.setModule(null); } } }
true
true
private void complete(ClassOrInterface klass, ClassMirror classMirror) { Map<MethodMirror, List<MethodMirror>> variables = new HashMap<MethodMirror, List<MethodMirror>>(); boolean isFromJDK = isFromJDK(classMirror); boolean isCeylon = (classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null); // now that everything has containers, do the inner classes if(klass instanceof Class == false || !((Class)klass).isOverloaded()){ // this will not load inner classes of overloads, but that's fine since we want them in the // abstracted super class (the real one) addInnerClasses(klass, classMirror); } // Java classes with multiple constructors get turned into multiple Ceylon classes // Here we get the specific constructor that was assigned to us (if any) MethodMirror constructor = null; if (klass instanceof LazyClass) { constructor = ((LazyClass)klass).getConstructor(); } // Turn a list of possibly overloaded methods into a map // of lists that contain methods with the same name Map<String, List<MethodMirror>> methods = new LinkedHashMap<String, List<MethodMirror>>(); for(MethodMirror methodMirror : classMirror.getDirectMethods()){ // We skip members marked with @Ignore if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(methodMirror.isStaticInit()) continue; if(isCeylon && methodMirror.isStatic()) continue; // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !methodMirror.isPublic()) continue; String methodName = methodMirror.getName(); List<MethodMirror> homonyms = methods.get(methodName); if (homonyms == null) { homonyms = new LinkedList<MethodMirror>(); methods.put(methodName, homonyms); } homonyms.add(methodMirror); } // Add the methods for(List<MethodMirror> methodMirrors : methods.values()){ boolean isOverloaded = methodMirrors.size() > 1; List<Declaration> overloads = (isOverloaded) ? new ArrayList<Declaration>(methodMirrors.size()) : null; for (MethodMirror methodMirror : methodMirrors) { String methodName = methodMirror.getName(); if(methodMirror.isConstructor()) { break; } else if(isGetter(methodMirror)) { // simple attribute addValue(klass, methodMirror, getJavaAttributeName(methodName), isCeylon); } else if(isSetter(methodMirror)) { // We skip setters for now and handle them later variables.put(methodMirror, methodMirrors); } else if(isHashAttribute(methodMirror)) { // ERASURE // Un-erasing 'hash' attribute from 'hashCode' method addValue(klass, methodMirror, "hash", isCeylon); } else if(isStringAttribute(methodMirror)) { // ERASURE // Un-erasing 'string' attribute from 'toString' method addValue(klass, methodMirror, "string", isCeylon); } else { // normal method Method m = addMethod(klass, methodMirror, isCeylon, isOverloaded); if (isOverloaded) { overloads.add(m); } } } if (overloads != null && !overloads.isEmpty()) { // We create an extra "abstraction" method for overloaded methods Method abstractionMethod = addMethod(klass, methodMirrors.get(0), false, false); abstractionMethod.setAbstraction(true); abstractionMethod.setOverloads(overloads); abstractionMethod.setType(new UnknownType(typeFactory).getType()); } } for(FieldMirror fieldMirror : classMirror.getDirectFields()){ // We skip members marked with @Ignore if(fieldMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(isCeylon && fieldMirror.isStatic()) continue; // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !fieldMirror.isPublic()) continue; String name = fieldMirror.getName(); // skip the field if "we've already got one" if(klass.getDirectMember(name, null, false) != null) continue; addValue(klass, fieldMirror, isCeylon); } // Having loaded methods and values, we can now set the constructor parameters if(constructor != null && (!(klass instanceof LazyClass) || !((LazyClass)klass).isTopLevelObjectType())) setParameters((Class)klass, constructor, isCeylon, klass); // Now marry-up attributes and parameters) if (klass instanceof Class) { for (Declaration m : klass.getMembers()) { if (Decl.isValue(m)) { Value v = (Value)m; Parameter p = ((Class)klass).getParameter(v.getName()); if (p != null) { p.setHidden(true); } } } } // Now mark all Values for which Setters exist as variable for(Entry<MethodMirror, List<MethodMirror>> setterEntry : variables.entrySet()){ MethodMirror setter = setterEntry.getKey(); String name = getJavaAttributeName(setter.getName()); Declaration decl = klass.getMember(name, null, false); boolean foundGetter = false; // skip Java fields, which we only get if there is no getter method, in that case just add the setter method if (decl instanceof Value && decl instanceof FieldValue == false) { Value value = (Value)decl; VariableMirror setterParam = setter.getParameters().get(0); ProducedType paramType = obtainType(setterParam.getType(), setterParam, klass, Decl.getModuleContainer(klass), VarianceLocation.INVARIANT, "setter '"+setter.getName()+"'", klass); // only add the setter if it has exactly the same type as the getter if(paramType.isExactly(value.getType())){ foundGetter = true; value.setVariable(true); if(decl instanceof JavaBeanValue) ((JavaBeanValue)decl).setSetterName(setter.getName()); }else logVerbose("Setter parameter type for "+name+" does not match corresponding getter type, adding setter as a method"); } if(!foundGetter){ // it was not a setter, it was a method, let's add it as such addMethod(klass, setter, isCeylon, false); } } // In some cases, where all constructors are ignored, we can end up with no constructor, so // pretend we have one which takes no parameters (eg. ceylon.language.String). if(klass instanceof Class && !((Class) klass).isAbstraction() && !klass.isAnonymous() && ((Class) klass).getParameterList() == null){ ((Class) klass).setParameterList(new ParameterList()); } setExtendedType(klass, classMirror); setSatisfiedTypes(klass, classMirror); setCaseTypes(klass, classMirror); fillRefinedDeclarations(klass); if(isCeylon) checkReifiedGenericsForMethods(klass, classMirror); setAnnotations(klass, classMirror); }
private void complete(ClassOrInterface klass, ClassMirror classMirror) { Map<MethodMirror, List<MethodMirror>> variables = new HashMap<MethodMirror, List<MethodMirror>>(); boolean isFromJDK = isFromJDK(classMirror); boolean isCeylon = (classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null); // now that everything has containers, do the inner classes if(klass instanceof Class == false || !((Class)klass).isOverloaded()){ // this will not load inner classes of overloads, but that's fine since we want them in the // abstracted super class (the real one) addInnerClasses(klass, classMirror); } // Java classes with multiple constructors get turned into multiple Ceylon classes // Here we get the specific constructor that was assigned to us (if any) MethodMirror constructor = null; if (klass instanceof LazyClass) { constructor = ((LazyClass)klass).getConstructor(); } // Turn a list of possibly overloaded methods into a map // of lists that contain methods with the same name Map<String, List<MethodMirror>> methods = new LinkedHashMap<String, List<MethodMirror>>(); for(MethodMirror methodMirror : classMirror.getDirectMethods()){ // We skip members marked with @Ignore if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(methodMirror.isStaticInit()) continue; if(isCeylon && methodMirror.isStatic()) continue; // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !methodMirror.isPublic()) continue; String methodName = methodMirror.getName(); List<MethodMirror> homonyms = methods.get(methodName); if (homonyms == null) { homonyms = new LinkedList<MethodMirror>(); methods.put(methodName, homonyms); } homonyms.add(methodMirror); } // Add the methods for(List<MethodMirror> methodMirrors : methods.values()){ boolean isOverloaded = methodMirrors.size() > 1; List<Declaration> overloads = (isOverloaded) ? new ArrayList<Declaration>(methodMirrors.size()) : null; for (MethodMirror methodMirror : methodMirrors) { String methodName = methodMirror.getName(); if(methodMirror.isConstructor()) { break; } else if(isGetter(methodMirror)) { // simple attribute addValue(klass, methodMirror, getJavaAttributeName(methodName), isCeylon); } else if(isSetter(methodMirror)) { // We skip setters for now and handle them later variables.put(methodMirror, methodMirrors); } else if(isHashAttribute(methodMirror)) { // ERASURE // Un-erasing 'hash' attribute from 'hashCode' method addValue(klass, methodMirror, "hash", isCeylon); } else if(isStringAttribute(methodMirror)) { // ERASURE // Un-erasing 'string' attribute from 'toString' method addValue(klass, methodMirror, "string", isCeylon); } else { // normal method Method m = addMethod(klass, methodMirror, isCeylon, isOverloaded); if (isOverloaded) { overloads.add(m); } } } if (overloads != null && !overloads.isEmpty()) { // We create an extra "abstraction" method for overloaded methods Method abstractionMethod = addMethod(klass, methodMirrors.get(0), false, false); abstractionMethod.setAbstraction(true); abstractionMethod.setOverloads(overloads); abstractionMethod.setType(new UnknownType(typeFactory).getType()); } } for(FieldMirror fieldMirror : classMirror.getDirectFields()){ // We skip members marked with @Ignore if(fieldMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(isCeylon && fieldMirror.isStatic()) continue; // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !fieldMirror.isPublic()) continue; String name = fieldMirror.getName(); // skip the field if "we've already got one" if(klass.getDirectMember(name, null, false) != null) continue; if (!"string".equals(fieldMirror.getName()) && ! "hash".equals(fieldMirror.getName())) { addValue(klass, fieldMirror, isCeylon); } } // Having loaded methods and values, we can now set the constructor parameters if(constructor != null && (!(klass instanceof LazyClass) || !((LazyClass)klass).isTopLevelObjectType())) setParameters((Class)klass, constructor, isCeylon, klass); // Now marry-up attributes and parameters) if (klass instanceof Class) { for (Declaration m : klass.getMembers()) { if (Decl.isValue(m)) { Value v = (Value)m; Parameter p = ((Class)klass).getParameter(v.getName()); if (p != null) { p.setHidden(true); } } } } // Now mark all Values for which Setters exist as variable for(Entry<MethodMirror, List<MethodMirror>> setterEntry : variables.entrySet()){ MethodMirror setter = setterEntry.getKey(); String name = getJavaAttributeName(setter.getName()); Declaration decl = klass.getMember(name, null, false); boolean foundGetter = false; // skip Java fields, which we only get if there is no getter method, in that case just add the setter method if (decl instanceof Value && decl instanceof FieldValue == false) { Value value = (Value)decl; VariableMirror setterParam = setter.getParameters().get(0); ProducedType paramType = obtainType(setterParam.getType(), setterParam, klass, Decl.getModuleContainer(klass), VarianceLocation.INVARIANT, "setter '"+setter.getName()+"'", klass); // only add the setter if it has exactly the same type as the getter if(paramType.isExactly(value.getType())){ foundGetter = true; value.setVariable(true); if(decl instanceof JavaBeanValue) ((JavaBeanValue)decl).setSetterName(setter.getName()); }else logVerbose("Setter parameter type for "+name+" does not match corresponding getter type, adding setter as a method"); } if(!foundGetter){ // it was not a setter, it was a method, let's add it as such addMethod(klass, setter, isCeylon, false); } } // In some cases, where all constructors are ignored, we can end up with no constructor, so // pretend we have one which takes no parameters (eg. ceylon.language.String). if(klass instanceof Class && !((Class) klass).isAbstraction() && !klass.isAnonymous() && ((Class) klass).getParameterList() == null){ ((Class) klass).setParameterList(new ParameterList()); } setExtendedType(klass, classMirror); setSatisfiedTypes(klass, classMirror); setCaseTypes(klass, classMirror); fillRefinedDeclarations(klass); if(isCeylon) checkReifiedGenericsForMethods(klass, classMirror); setAnnotations(klass, classMirror); }
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/deserializer/ScriptMediatorDeserializer.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/deserializer/ScriptMediatorDeserializer.java index 1d6c397ce..72cfcb92c 100644 --- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/deserializer/ScriptMediatorDeserializer.java +++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/deserializer/ScriptMediatorDeserializer.java @@ -1,75 +1,75 @@ /* * Copyright 2012 WSO2, Inc. (http://wso2.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.deserializer; import java.util.Set; import org.apache.synapse.mediators.AbstractMediator; import org.apache.synapse.mediators.Value; import org.apache.synapse.util.xpath.SynapseXPath; import org.eclipse.core.runtime.Assert; import org.eclipse.emf.common.util.BasicEList; import org.eclipse.emf.common.util.EList; import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory; import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage; import org.wso2.developerstudio.eclipse.gmf.esb.NamespacedProperty; import org.wso2.developerstudio.eclipse.gmf.esb.RegistryKeyProperty; import org.wso2.developerstudio.eclipse.gmf.esb.ScriptMediator; import org.wso2.developerstudio.eclipse.gmf.esb.ScriptType; import org.wso2.developerstudio.eclipse.gmf.esb.scriptKeyTypeEnum; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbElementTypes; public class ScriptMediatorDeserializer extends AbstractEsbNodeDeserializer<AbstractMediator, ScriptMediator>{ public ScriptMediator createNode(IGraphicalEditPart part,AbstractMediator mediator) { Assert.isTrue(mediator instanceof org.apache.synapse.mediators.bsf.ScriptMediator, "Unsupported mediator passed in for deserialization at "+ this.getClass()); org.apache.synapse.mediators.bsf.ScriptMediator scriptMediator = (org.apache.synapse.mediators.bsf.ScriptMediator)mediator; ScriptMediator visualScriptMediator = (ScriptMediator) DeserializerUtils.createNode(part, EsbElementTypes.ScriptMediator_3508); setElementToEdit(visualScriptMediator); String type = scriptMediator.getScriptSrc(); executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_LANGUAGE, scriptMediator.getLanguage()); if(type!=null){ executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_TYPE, ScriptType.INLINE); executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_BODY, scriptMediator.getScriptSrc()); }else{ executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_TYPE, ScriptType.REGISTRY_REFERENCE); Set<Value> keySet = scriptMediator.getIncludeMap().keySet(); - EList<Value> keylis = new BasicEList<Value>(); for (Value value : keySet) { - keylis.add(value); + RegistryKeyProperty keyProperty=EsbFactory.eINSTANCE.createRegistryKeyProperty(); + keyProperty.setKeyValue(value.getKeyValue()); + executeAddValueCommand(visualScriptMediator.getScriptKeys(),keyProperty); } - executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_KEYS, keylis); Value key = scriptMediator.getKey(); SynapseXPath expression = key.getExpression(); String keyValue = key.getKeyValue(); if(expression!=null){ NamespacedProperty namespacedProperty = createNamespacedProperty(expression); executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__KEY_TYPE, scriptKeyTypeEnum.DYNAMIC_KEY); executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_DYNAMIC_KEY, namespacedProperty); }else if(keyValue!=null){ RegistryKeyProperty registryKeyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty(); registryKeyProperty.setKeyValue(keyValue); executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__KEY_TYPE, scriptKeyTypeEnum.STATIC_KEY); executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_DYNAMIC_KEY, registryKeyProperty); } executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__MEDIATE_FUNCTION, scriptMediator.getFunction()); } return visualScriptMediator; } }
false
true
public ScriptMediator createNode(IGraphicalEditPart part,AbstractMediator mediator) { Assert.isTrue(mediator instanceof org.apache.synapse.mediators.bsf.ScriptMediator, "Unsupported mediator passed in for deserialization at "+ this.getClass()); org.apache.synapse.mediators.bsf.ScriptMediator scriptMediator = (org.apache.synapse.mediators.bsf.ScriptMediator)mediator; ScriptMediator visualScriptMediator = (ScriptMediator) DeserializerUtils.createNode(part, EsbElementTypes.ScriptMediator_3508); setElementToEdit(visualScriptMediator); String type = scriptMediator.getScriptSrc(); executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_LANGUAGE, scriptMediator.getLanguage()); if(type!=null){ executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_TYPE, ScriptType.INLINE); executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_BODY, scriptMediator.getScriptSrc()); }else{ executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_TYPE, ScriptType.REGISTRY_REFERENCE); Set<Value> keySet = scriptMediator.getIncludeMap().keySet(); EList<Value> keylis = new BasicEList<Value>(); for (Value value : keySet) { keylis.add(value); } executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_KEYS, keylis); Value key = scriptMediator.getKey(); SynapseXPath expression = key.getExpression(); String keyValue = key.getKeyValue(); if(expression!=null){ NamespacedProperty namespacedProperty = createNamespacedProperty(expression); executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__KEY_TYPE, scriptKeyTypeEnum.DYNAMIC_KEY); executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_DYNAMIC_KEY, namespacedProperty); }else if(keyValue!=null){ RegistryKeyProperty registryKeyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty(); registryKeyProperty.setKeyValue(keyValue); executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__KEY_TYPE, scriptKeyTypeEnum.STATIC_KEY); executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_DYNAMIC_KEY, registryKeyProperty); } executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__MEDIATE_FUNCTION, scriptMediator.getFunction()); } return visualScriptMediator; }
public ScriptMediator createNode(IGraphicalEditPart part,AbstractMediator mediator) { Assert.isTrue(mediator instanceof org.apache.synapse.mediators.bsf.ScriptMediator, "Unsupported mediator passed in for deserialization at "+ this.getClass()); org.apache.synapse.mediators.bsf.ScriptMediator scriptMediator = (org.apache.synapse.mediators.bsf.ScriptMediator)mediator; ScriptMediator visualScriptMediator = (ScriptMediator) DeserializerUtils.createNode(part, EsbElementTypes.ScriptMediator_3508); setElementToEdit(visualScriptMediator); String type = scriptMediator.getScriptSrc(); executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_LANGUAGE, scriptMediator.getLanguage()); if(type!=null){ executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_TYPE, ScriptType.INLINE); executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_BODY, scriptMediator.getScriptSrc()); }else{ executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_TYPE, ScriptType.REGISTRY_REFERENCE); Set<Value> keySet = scriptMediator.getIncludeMap().keySet(); for (Value value : keySet) { RegistryKeyProperty keyProperty=EsbFactory.eINSTANCE.createRegistryKeyProperty(); keyProperty.setKeyValue(value.getKeyValue()); executeAddValueCommand(visualScriptMediator.getScriptKeys(),keyProperty); } Value key = scriptMediator.getKey(); SynapseXPath expression = key.getExpression(); String keyValue = key.getKeyValue(); if(expression!=null){ NamespacedProperty namespacedProperty = createNamespacedProperty(expression); executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__KEY_TYPE, scriptKeyTypeEnum.DYNAMIC_KEY); executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_DYNAMIC_KEY, namespacedProperty); }else if(keyValue!=null){ RegistryKeyProperty registryKeyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty(); registryKeyProperty.setKeyValue(keyValue); executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__KEY_TYPE, scriptKeyTypeEnum.STATIC_KEY); executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__SCRIPT_DYNAMIC_KEY, registryKeyProperty); } executeSetValueCommand(EsbPackage.Literals.SCRIPT_MEDIATOR__MEDIATE_FUNCTION, scriptMediator.getFunction()); } return visualScriptMediator; }
diff --git a/src/simpleserver/command/MyAreaCommand.java b/src/simpleserver/command/MyAreaCommand.java index ceeb364..ec3a156 100644 --- a/src/simpleserver/command/MyAreaCommand.java +++ b/src/simpleserver/command/MyAreaCommand.java @@ -1,168 +1,167 @@ /* * Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package simpleserver.command; import static simpleserver.lang.Translations.t; import java.util.Set; import simpleserver.Color; import simpleserver.Player; import simpleserver.config.xml.AllBlocks; import simpleserver.config.xml.Area; import simpleserver.config.xml.Chests; import simpleserver.config.xml.Config; import simpleserver.config.xml.DimensionConfig; import simpleserver.config.xml.Permission; import simpleserver.config.xml.Config.AreaStoragePair; public class MyAreaCommand extends AbstractCommand implements PlayerCommand { private static final byte DEFAULT_SIZE = 50; public MyAreaCommand() { super("myarea [start|end|save|unsave|rename]", "Manage your personal area"); } private boolean areaSizeOk(Player player, int[] size) { return (Math.abs(player.areastart.x() - player.areaend.x()) < size[0]) && (Math.abs(player.areastart.z() - player.areaend.z()) < size[1]) && player.areaend.dimension() == player.areastart.dimension(); } private int[] getAreaMax(Player player) { // Get the maximum area sizes from config.xml int[] size = { Math.abs(player.getServer().config.properties.getInt("areaMaxX")), Math.abs(player.getServer().config.properties.getInt("areaMaxZ")) }; // Check to make sure the configuration is valid // If not, reset to default size for (byte i = 0; i < size.length; i++) { if (size[i] <= 0 || Integer.valueOf(size[i]) == null) { size[i] = DEFAULT_SIZE; } } return size; } public void execute(Player player, String message) { // Set up an integer array to hold the maximum area size int[] maxSize = getAreaMax(player); // X, Z Config config = player.getServer().config; String arguments[] = extractArguments(message); if (arguments.length == 0) { player.addTCaptionedMessage("Usage", commandPrefix() + "myarea [start|end|save|unsave|rename]"); return; } if (arguments[0].equals("start")) { player.areastart = player.position(); player.areastart = player.areastart.setY((byte) 0); // no height limit player.addTMessage(Color.GRAY, "Start coordinate set."); } else if (arguments[0].equals("end")) { player.areaend = player.position(); player.areaend = player.areaend.setY((byte) 127); // no height limit - // Save the player a step by checking area size after end coord set - if (!areaSizeOk(player, maxSize)) { - player.addTMessage(Color.RED, "Your area is allowed to have a maximum size of " + - maxSize[0] + "x" + maxSize[1] + "!"); - return; - } player.addTMessage(Color.GRAY, "End coordinate set."); } else if (arguments[0].equals("save")) { if (player.areastart == null || player.areaend == null) { player.addTMessage(Color.RED, "Define start and end coordinates for your area first!"); return; } + if (!areaSizeOk(player, maxSize)) { + player.addTMessage(Color.RED, "Your area is allowed to have a maximum size of " + + maxSize[0] + "x" + maxSize[1] + "!"); + return; + } if (player.getServer().config.playerArea(player) != null) { player.addTMessage(Color.RED, "New area can not be saved before you remove your old one!"); return; } Area area = createPlayerArea(player); Set<Area> overlaps = config.dimensions.overlaps(area); if (!overlaps.isEmpty()) { player.addTMessage(Color.RED, "Your area overlaps with other areas and could therefore not be saved!"); StringBuilder str = new StringBuilder(); for (Area overlap : overlaps) { str.append(overlap.name); str.append(", "); } str.delete(str.length() - 2, str.length() - 1); player.addTCaptionedMessage("Overlapping areas", "%s", str); return; } saveArea(area, player); player.addTMessage(Color.GRAY, "Your area has been saved!"); } else if (arguments[0].equals("unsave") || arguments[0].equals("remove")) { AreaStoragePair area = config.playerArea(player); if (area == null) { player.addTMessage(Color.RED, "You currently have no personal area which can be removed!"); return; } area.storage.remove(area.area); player.addTMessage(Color.GRAY, "Your area has been removed!"); player.getServer().saveConfig(); } else if (arguments[0].equals("rename")) { AreaStoragePair area = config.playerArea(player); if (area == null) { player.addTMessage(Color.RED, "You currently have no personal area which can be renamed!"); return; } String label = extractArgument(message, 1); if (label != null) { area.area.name = label; player.addTMessage(Color.GRAY, "Your area has been renamed!"); player.getServer().saveConfig(); } else { player.addTMessage(Color.RED, "Please supply an area name."); } } else { player.addTMessage(Color.RED, "You entered an invalid argument."); } } private Area createPlayerArea(Player player) { Area area = new Area(t("%s's area", player.getName()), player.areastart, player.areaend); area.owner = player.getName().toLowerCase(); Permission perm = new Permission(player); AllBlocks blocks = new AllBlocks(); blocks.destroy = perm; blocks.place = perm; blocks.use = perm; area.allblocks.blocks = blocks; area.chests.chests = new Chests(perm); return area; } private void saveArea(Area area, Player player) { DimensionConfig dimension = player.getServer().config.dimensions.get(area.start.dimension()); if (dimension == null) { dimension = player.getServer().config.dimensions.add(area.start.dimension()); } dimension.add(area); player.getServer().saveConfig(); } }
false
true
public void execute(Player player, String message) { // Set up an integer array to hold the maximum area size int[] maxSize = getAreaMax(player); // X, Z Config config = player.getServer().config; String arguments[] = extractArguments(message); if (arguments.length == 0) { player.addTCaptionedMessage("Usage", commandPrefix() + "myarea [start|end|save|unsave|rename]"); return; } if (arguments[0].equals("start")) { player.areastart = player.position(); player.areastart = player.areastart.setY((byte) 0); // no height limit player.addTMessage(Color.GRAY, "Start coordinate set."); } else if (arguments[0].equals("end")) { player.areaend = player.position(); player.areaend = player.areaend.setY((byte) 127); // no height limit // Save the player a step by checking area size after end coord set if (!areaSizeOk(player, maxSize)) { player.addTMessage(Color.RED, "Your area is allowed to have a maximum size of " + maxSize[0] + "x" + maxSize[1] + "!"); return; } player.addTMessage(Color.GRAY, "End coordinate set."); } else if (arguments[0].equals("save")) { if (player.areastart == null || player.areaend == null) { player.addTMessage(Color.RED, "Define start and end coordinates for your area first!"); return; } if (player.getServer().config.playerArea(player) != null) { player.addTMessage(Color.RED, "New area can not be saved before you remove your old one!"); return; } Area area = createPlayerArea(player); Set<Area> overlaps = config.dimensions.overlaps(area); if (!overlaps.isEmpty()) { player.addTMessage(Color.RED, "Your area overlaps with other areas and could therefore not be saved!"); StringBuilder str = new StringBuilder(); for (Area overlap : overlaps) { str.append(overlap.name); str.append(", "); } str.delete(str.length() - 2, str.length() - 1); player.addTCaptionedMessage("Overlapping areas", "%s", str); return; } saveArea(area, player); player.addTMessage(Color.GRAY, "Your area has been saved!"); } else if (arguments[0].equals("unsave") || arguments[0].equals("remove")) { AreaStoragePair area = config.playerArea(player); if (area == null) { player.addTMessage(Color.RED, "You currently have no personal area which can be removed!"); return; } area.storage.remove(area.area); player.addTMessage(Color.GRAY, "Your area has been removed!"); player.getServer().saveConfig(); } else if (arguments[0].equals("rename")) { AreaStoragePair area = config.playerArea(player); if (area == null) { player.addTMessage(Color.RED, "You currently have no personal area which can be renamed!"); return; } String label = extractArgument(message, 1); if (label != null) { area.area.name = label; player.addTMessage(Color.GRAY, "Your area has been renamed!"); player.getServer().saveConfig(); } else { player.addTMessage(Color.RED, "Please supply an area name."); } } else { player.addTMessage(Color.RED, "You entered an invalid argument."); } }
public void execute(Player player, String message) { // Set up an integer array to hold the maximum area size int[] maxSize = getAreaMax(player); // X, Z Config config = player.getServer().config; String arguments[] = extractArguments(message); if (arguments.length == 0) { player.addTCaptionedMessage("Usage", commandPrefix() + "myarea [start|end|save|unsave|rename]"); return; } if (arguments[0].equals("start")) { player.areastart = player.position(); player.areastart = player.areastart.setY((byte) 0); // no height limit player.addTMessage(Color.GRAY, "Start coordinate set."); } else if (arguments[0].equals("end")) { player.areaend = player.position(); player.areaend = player.areaend.setY((byte) 127); // no height limit player.addTMessage(Color.GRAY, "End coordinate set."); } else if (arguments[0].equals("save")) { if (player.areastart == null || player.areaend == null) { player.addTMessage(Color.RED, "Define start and end coordinates for your area first!"); return; } if (!areaSizeOk(player, maxSize)) { player.addTMessage(Color.RED, "Your area is allowed to have a maximum size of " + maxSize[0] + "x" + maxSize[1] + "!"); return; } if (player.getServer().config.playerArea(player) != null) { player.addTMessage(Color.RED, "New area can not be saved before you remove your old one!"); return; } Area area = createPlayerArea(player); Set<Area> overlaps = config.dimensions.overlaps(area); if (!overlaps.isEmpty()) { player.addTMessage(Color.RED, "Your area overlaps with other areas and could therefore not be saved!"); StringBuilder str = new StringBuilder(); for (Area overlap : overlaps) { str.append(overlap.name); str.append(", "); } str.delete(str.length() - 2, str.length() - 1); player.addTCaptionedMessage("Overlapping areas", "%s", str); return; } saveArea(area, player); player.addTMessage(Color.GRAY, "Your area has been saved!"); } else if (arguments[0].equals("unsave") || arguments[0].equals("remove")) { AreaStoragePair area = config.playerArea(player); if (area == null) { player.addTMessage(Color.RED, "You currently have no personal area which can be removed!"); return; } area.storage.remove(area.area); player.addTMessage(Color.GRAY, "Your area has been removed!"); player.getServer().saveConfig(); } else if (arguments[0].equals("rename")) { AreaStoragePair area = config.playerArea(player); if (area == null) { player.addTMessage(Color.RED, "You currently have no personal area which can be renamed!"); return; } String label = extractArgument(message, 1); if (label != null) { area.area.name = label; player.addTMessage(Color.GRAY, "Your area has been renamed!"); player.getServer().saveConfig(); } else { player.addTMessage(Color.RED, "Please supply an area name."); } } else { player.addTMessage(Color.RED, "You entered an invalid argument."); } }
diff --git a/src/main/java/hudson/plugins/nodenamecolumn/NodeNameColumn.java b/src/main/java/hudson/plugins/nodenamecolumn/NodeNameColumn.java index 1c8ab0c..e4877c7 100644 --- a/src/main/java/hudson/plugins/nodenamecolumn/NodeNameColumn.java +++ b/src/main/java/hudson/plugins/nodenamecolumn/NodeNameColumn.java @@ -1,106 +1,115 @@ /* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Alan Harder * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.plugins.nodenamecolumn; import hudson.Extension; import hudson.XmlFile; import hudson.matrix.MatrixProject; import hudson.maven.MavenModuleSet; import hudson.model.Descriptor; import hudson.model.Job; import hudson.model.FreeStyleProject; import hudson.views.ListViewColumn; import java.io.IOException; import net.sf.json.JSONObject; import org.kohsuke.stapler.StaplerRequest; /** * View column that shows the node name by parsing the configuration. * * @author Kalpana Nagireddy */ public class NodeNameColumn extends ListViewColumn { public String getNodeName(Job job) { String name=""; XmlFile configXmlFile = job.getConfigFile(); try{ Object obj = configXmlFile.read(); name = getName(obj, job.getClass().getSimpleName()); }catch(IOException ex){ //Exception in reading config file } return name; } public enum JobTypeEnum{ FreeStyleProject, MavenModuleSet, MatrixProject; } @Extension public static final Descriptor<ListViewColumn> DESCRIPTOR = new DescriptorImpl(); public Descriptor<ListViewColumn> getDescriptor() { return DESCRIPTOR; } private String getName(Object obj, String type){ String name = null; final JobTypeEnum jobType; try { jobType = JobTypeEnum.valueOf(type); } catch(IllegalArgumentException e) { throw new RuntimeException("String has no matching NumeralEnum value"); } - switch (jobType){ - case FreeStyleProject: - name = ((FreeStyleProject)obj).getAssignedLabel().getName(); - break; - case MavenModuleSet: - name = ((MavenModuleSet)obj).getAssignedLabel().getName(); - break; - case MatrixProject: - name = ((MatrixProject)obj).getAssignedLabel().getName(); - break; - default: - name = "N/A"; + name = "N/A"; + if (obj != null){ + switch (jobType){ + case FreeStyleProject: + if (((FreeStyleProject)obj).getAssignedLabel() != null) { + name = ((FreeStyleProject)obj).getAssignedLabel().getName(); + } + break; + case MavenModuleSet: + if (((MavenModuleSet)obj).getAssignedLabel() != null){ + name = ((MavenModuleSet)obj).getAssignedLabel().getName(); + } + break; + case MatrixProject: + if (((MatrixProject)obj).getAssignedLabel() != null){ + name = ((MatrixProject)obj).getAssignedLabel().getName(); + } + break; + default: + name = "N/A"; + } } return name; } private static class DescriptorImpl extends Descriptor<ListViewColumn> { @Override public ListViewColumn newInstance(StaplerRequest req, JSONObject formData) throws FormException { return new NodeNameColumn(); } @Override public String getDisplayName() { return Messages.NodeNameColumn_DisplayName(); } } }
false
true
private String getName(Object obj, String type){ String name = null; final JobTypeEnum jobType; try { jobType = JobTypeEnum.valueOf(type); } catch(IllegalArgumentException e) { throw new RuntimeException("String has no matching NumeralEnum value"); } switch (jobType){ case FreeStyleProject: name = ((FreeStyleProject)obj).getAssignedLabel().getName(); break; case MavenModuleSet: name = ((MavenModuleSet)obj).getAssignedLabel().getName(); break; case MatrixProject: name = ((MatrixProject)obj).getAssignedLabel().getName(); break; default: name = "N/A"; } return name; }
private String getName(Object obj, String type){ String name = null; final JobTypeEnum jobType; try { jobType = JobTypeEnum.valueOf(type); } catch(IllegalArgumentException e) { throw new RuntimeException("String has no matching NumeralEnum value"); } name = "N/A"; if (obj != null){ switch (jobType){ case FreeStyleProject: if (((FreeStyleProject)obj).getAssignedLabel() != null) { name = ((FreeStyleProject)obj).getAssignedLabel().getName(); } break; case MavenModuleSet: if (((MavenModuleSet)obj).getAssignedLabel() != null){ name = ((MavenModuleSet)obj).getAssignedLabel().getName(); } break; case MatrixProject: if (((MatrixProject)obj).getAssignedLabel() != null){ name = ((MatrixProject)obj).getAssignedLabel().getName(); } break; default: name = "N/A"; } } return name; }
diff --git a/jeeves/src/main/java/jeeves/config/springutil/MultiNodeAuthenticationFilter.java b/jeeves/src/main/java/jeeves/config/springutil/MultiNodeAuthenticationFilter.java index 37dd60e78a..71ab4f79ca 100644 --- a/jeeves/src/main/java/jeeves/config/springutil/MultiNodeAuthenticationFilter.java +++ b/jeeves/src/main/java/jeeves/config/springutil/MultiNodeAuthenticationFilter.java @@ -1,133 +1,133 @@ package jeeves.config.springutil; import com.google.common.escape.Escaper; import com.google.common.net.UrlEscapers; import jeeves.constants.Jeeves; import jeeves.server.sources.ServiceRequestFactory; import jeeves.server.sources.http.JeevesServlet; import org.fao.geonet.Constants; import org.fao.geonet.NodeInfo; import org.fao.geonet.domain.User; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.GenericFilterBean; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static jeeves.config.springutil.JeevesDelegatingFilterProxy.getApplicationContextFromServletContext; /** * This filter is designed to ensure that users logged in one node is not logged in in the others. * <p/> * User: Jesse * Date: 11/26/13 * Time: 7:24 AM */ public class MultiNodeAuthenticationFilter extends GenericFilterBean { private String _location; public void setLocation(String location) { this._location = location; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final SecurityContext context = SecurityContextHolder.getContext(); if (context != null) { final Authentication user = context.getAuthentication(); if (user != null) { final ConfigurableApplicationContext appContext = getApplicationContextFromServletContext(getServletContext()); final String nodeId = appContext.getBean(NodeInfo.class).getId(); final HttpServletRequest httpServletRequest = (HttpServletRequest) request; final String lang = getRequestLanguage(appContext, httpServletRequest); final String redirectedFrom = httpServletRequest.getRequestURI(); String oldNodeId = null; for (GrantedAuthority grantedAuthority : user.getAuthorities()) { String authName = grantedAuthority.getAuthority(); if (authName.startsWith(User.NODE_APPLICATION_CONTEXT_KEY)) { oldNodeId = authName.substring(User.NODE_APPLICATION_CONTEXT_KEY.length()); break; } } if (getServletContext().getAttribute(User.NODE_APPLICATION_CONTEXT_KEY + oldNodeId) == null) { // the application context associated with the node id doesn't exist so log user out. SecurityContextHolder.clearContext(); } else if (_location != null) { if (oldNodeId != null && !oldNodeId.equals(nodeId)) { final Escaper escaper = UrlEscapers.urlFormParameterEscaper(); final String location = getServletContext().getContextPath() + _location.replace("@@lang@@", escaper.escape(lang)) .replace("@@nodeId@@", escaper.escape(nodeId)) .replace("@@redirectedFrom@@", escaper.escape(redirectedFrom)) .replace("@@oldNodeId@@", escaper.escape(oldNodeId)) .replace("@@oldUserName@@", escaper.escape(user.getName())); String requestURI = httpServletRequest.getRequestURI(); // drop the ! at the end so we can view the xml of the warning page if (requestURI.endsWith("!")) { requestURI = requestURI.substring(0, requestURI.length() - 1); } final boolean isNodeWarningPage = requestURI.equals(location.split("\\?")[0]); - if (!isNodeWarningPage && (oldNodeId != null && !oldNodeId.equals(nodeId))) { + if (!isNodeWarningPage) { HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.sendRedirect(httpServletResponse.encodeRedirectURL(location)); return; } } } else { throwAuthError(); } } } chain.doFilter(request, response); } private String getRequestLanguage(ConfigurableApplicationContext appContext, HttpServletRequest request) { String language = request.getParameter("hl"); if (language == null) { final Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals(Jeeves.LANG_COOKIE)) { language = cookie.getValue(); break; } } } if (language == null) { String pathInfo = request.getPathInfo(); language = ServiceRequestFactory.extractLanguage(pathInfo); } if (language == null) { language = appContext.getBean("defaultLanguage", String.class); } if (language == null) { language = "eng"; } return language; } private void throwAuthError() { throw new WrongNodeAuthenticationException( "The current user was logged into a different node. " + "To login to this node the user must logout and login to the new node. " + "It is also possible to return to the old node."); } }
true
true
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final SecurityContext context = SecurityContextHolder.getContext(); if (context != null) { final Authentication user = context.getAuthentication(); if (user != null) { final ConfigurableApplicationContext appContext = getApplicationContextFromServletContext(getServletContext()); final String nodeId = appContext.getBean(NodeInfo.class).getId(); final HttpServletRequest httpServletRequest = (HttpServletRequest) request; final String lang = getRequestLanguage(appContext, httpServletRequest); final String redirectedFrom = httpServletRequest.getRequestURI(); String oldNodeId = null; for (GrantedAuthority grantedAuthority : user.getAuthorities()) { String authName = grantedAuthority.getAuthority(); if (authName.startsWith(User.NODE_APPLICATION_CONTEXT_KEY)) { oldNodeId = authName.substring(User.NODE_APPLICATION_CONTEXT_KEY.length()); break; } } if (getServletContext().getAttribute(User.NODE_APPLICATION_CONTEXT_KEY + oldNodeId) == null) { // the application context associated with the node id doesn't exist so log user out. SecurityContextHolder.clearContext(); } else if (_location != null) { if (oldNodeId != null && !oldNodeId.equals(nodeId)) { final Escaper escaper = UrlEscapers.urlFormParameterEscaper(); final String location = getServletContext().getContextPath() + _location.replace("@@lang@@", escaper.escape(lang)) .replace("@@nodeId@@", escaper.escape(nodeId)) .replace("@@redirectedFrom@@", escaper.escape(redirectedFrom)) .replace("@@oldNodeId@@", escaper.escape(oldNodeId)) .replace("@@oldUserName@@", escaper.escape(user.getName())); String requestURI = httpServletRequest.getRequestURI(); // drop the ! at the end so we can view the xml of the warning page if (requestURI.endsWith("!")) { requestURI = requestURI.substring(0, requestURI.length() - 1); } final boolean isNodeWarningPage = requestURI.equals(location.split("\\?")[0]); if (!isNodeWarningPage && (oldNodeId != null && !oldNodeId.equals(nodeId))) { HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.sendRedirect(httpServletResponse.encodeRedirectURL(location)); return; } } } else { throwAuthError(); } } } chain.doFilter(request, response); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final SecurityContext context = SecurityContextHolder.getContext(); if (context != null) { final Authentication user = context.getAuthentication(); if (user != null) { final ConfigurableApplicationContext appContext = getApplicationContextFromServletContext(getServletContext()); final String nodeId = appContext.getBean(NodeInfo.class).getId(); final HttpServletRequest httpServletRequest = (HttpServletRequest) request; final String lang = getRequestLanguage(appContext, httpServletRequest); final String redirectedFrom = httpServletRequest.getRequestURI(); String oldNodeId = null; for (GrantedAuthority grantedAuthority : user.getAuthorities()) { String authName = grantedAuthority.getAuthority(); if (authName.startsWith(User.NODE_APPLICATION_CONTEXT_KEY)) { oldNodeId = authName.substring(User.NODE_APPLICATION_CONTEXT_KEY.length()); break; } } if (getServletContext().getAttribute(User.NODE_APPLICATION_CONTEXT_KEY + oldNodeId) == null) { // the application context associated with the node id doesn't exist so log user out. SecurityContextHolder.clearContext(); } else if (_location != null) { if (oldNodeId != null && !oldNodeId.equals(nodeId)) { final Escaper escaper = UrlEscapers.urlFormParameterEscaper(); final String location = getServletContext().getContextPath() + _location.replace("@@lang@@", escaper.escape(lang)) .replace("@@nodeId@@", escaper.escape(nodeId)) .replace("@@redirectedFrom@@", escaper.escape(redirectedFrom)) .replace("@@oldNodeId@@", escaper.escape(oldNodeId)) .replace("@@oldUserName@@", escaper.escape(user.getName())); String requestURI = httpServletRequest.getRequestURI(); // drop the ! at the end so we can view the xml of the warning page if (requestURI.endsWith("!")) { requestURI = requestURI.substring(0, requestURI.length() - 1); } final boolean isNodeWarningPage = requestURI.equals(location.split("\\?")[0]); if (!isNodeWarningPage) { HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.sendRedirect(httpServletResponse.encodeRedirectURL(location)); return; } } } else { throwAuthError(); } } } chain.doFilter(request, response); }
diff --git a/jing/rxnSys/ConversionTT.java b/jing/rxnSys/ConversionTT.java index e4c20b0c..9f02e24b 100644 --- a/jing/rxnSys/ConversionTT.java +++ b/jing/rxnSys/ConversionTT.java @@ -1,123 +1,130 @@ //////////////////////////////////////////////////////////////////////////////// // // RMG - Reaction Mechanism Generator // // Copyright (c) 2002-2009 Prof. William H. Green ([email protected]) and the // RMG Team ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // //////////////////////////////////////////////////////////////////////////////// package jing.rxnSys; import jing.chem.*; import java.util.*; //## package jing::rxnSys //---------------------------------------------------------------------------- // jing\rxnSys\ConversionTT.java //---------------------------------------------------------------------------- /** Using conversion to control the termination of reaction systerm. ie, reaction terminates at a given conversion of some important reactants. */ //## class ConversionTT public class ConversionTT implements TerminationTester { protected LinkedList speciesGoalConversionSet; // Constructors //## operation ConversionTT() private ConversionTT() { { speciesGoalConversionSet=new LinkedList(); } //#[ operation ConversionTT() //#] } //## operation ConversionTT(HashSet) public ConversionTT(LinkedList p_scs) { { speciesGoalConversionSet=new LinkedList(); } //#[ operation ConversionTT(HashSet) speciesGoalConversionSet = p_scs; //#] } //## operation deleteSpeciesConversionSet(SpeciesConversion) public void deleteSpeciesConversionSet(SpeciesConversion p_SpeciesConversion) { //#[ operation deleteSpeciesConversionSet(SpeciesConversion) speciesGoalConversionSet.remove(p_SpeciesConversion); p_SpeciesConversion=null; //#] } //## operation isReactionTerminated(InitialStatus,PresentStatus) public boolean isReactionTerminated(InitialStatus p_initialStatus, PresentStatus p_presentStatus) { //#[ operation isReactionTerminated(InitialStatus,PresentStatus) Iterator iter = speciesGoalConversionSet.iterator(); while (iter.hasNext()) { SpeciesConversion sc = (SpeciesConversion)iter.next(); Species spe = sc.getSpecies(); SpeciesStatus iss = p_initialStatus.getSpeciesStatus(spe); SpeciesStatus pss = p_presentStatus.getSpeciesStatus(spe); double init_conc = iss.getConcentration(); double pres_conc = pss.getConcentration(); - if (pres_conc>init_conc || init_conc == 0) throw new InvalidConversionException(); + /* MRH on 1-Jun-2009 + Updated from pres_conc>init_conc to pres_conc>1.01*init_conc + For certain cases, ODESovler would fail on the first step + The ODESolver would change the limiting reactant concentration + from 5.xxxxxxx3e-7 to 5.xxxxxxx5e-7 (for example), thus causing + RMG to throw an exception. + */ + if (pres_conc>(1.01*init_conc) || init_conc == 0) throw new InvalidConversionException(); double conversion = (init_conc-pres_conc)/init_conc; if (conversion < sc.getConversion()) return false; } return true; //#] } public Iterator getSpeciesGoalConversionSet() { Iterator iter=speciesGoalConversionSet.iterator(); return iter; } //11/1/07 gmagoon: created alternate accessor to return LinkedList; UPDATE: not needed //public LinkedList getSpeciesGoalConversionSetList(){ // return speciesGoalConversionSet; //} public void addSpeciesGoalConversionSet(SpeciesConversion p_SpeciesConversion) { speciesGoalConversionSet.add(p_SpeciesConversion); } public void removeSpeciesGoalConversionSet(SpeciesConversion p_SpeciesConversion) { speciesGoalConversionSet.remove(p_SpeciesConversion); } public void clearSpeciesGoalConversionSet() { speciesGoalConversionSet.clear(); } } /********************************************************************* File Path : RMG\RMG\jing\rxnSys\ConversionTT.java *********************************************************************/
true
true
public boolean isReactionTerminated(InitialStatus p_initialStatus, PresentStatus p_presentStatus) { //#[ operation isReactionTerminated(InitialStatus,PresentStatus) Iterator iter = speciesGoalConversionSet.iterator(); while (iter.hasNext()) { SpeciesConversion sc = (SpeciesConversion)iter.next(); Species spe = sc.getSpecies(); SpeciesStatus iss = p_initialStatus.getSpeciesStatus(spe); SpeciesStatus pss = p_presentStatus.getSpeciesStatus(spe); double init_conc = iss.getConcentration(); double pres_conc = pss.getConcentration(); if (pres_conc>init_conc || init_conc == 0) throw new InvalidConversionException(); double conversion = (init_conc-pres_conc)/init_conc; if (conversion < sc.getConversion()) return false; } return true; //#] }
public boolean isReactionTerminated(InitialStatus p_initialStatus, PresentStatus p_presentStatus) { //#[ operation isReactionTerminated(InitialStatus,PresentStatus) Iterator iter = speciesGoalConversionSet.iterator(); while (iter.hasNext()) { SpeciesConversion sc = (SpeciesConversion)iter.next(); Species spe = sc.getSpecies(); SpeciesStatus iss = p_initialStatus.getSpeciesStatus(spe); SpeciesStatus pss = p_presentStatus.getSpeciesStatus(spe); double init_conc = iss.getConcentration(); double pres_conc = pss.getConcentration(); /* MRH on 1-Jun-2009 Updated from pres_conc>init_conc to pres_conc>1.01*init_conc For certain cases, ODESovler would fail on the first step The ODESolver would change the limiting reactant concentration from 5.xxxxxxx3e-7 to 5.xxxxxxx5e-7 (for example), thus causing RMG to throw an exception. */ if (pres_conc>(1.01*init_conc) || init_conc == 0) throw new InvalidConversionException(); double conversion = (init_conc-pres_conc)/init_conc; if (conversion < sc.getConversion()) return false; } return true; //#] }
diff --git a/src/com/github/norwae/whatiread/MainActivity.java b/src/com/github/norwae/whatiread/MainActivity.java index 726cb1b..2fd3793 100644 --- a/src/com/github/norwae/whatiread/MainActivity.java +++ b/src/com/github/norwae/whatiread/MainActivity.java @@ -1,194 +1,194 @@ package com.github.norwae.whatiread; import java.util.Collection; import java.util.HashSet; import com.github.norwae.whatiread.data.BookInfo; import com.github.norwae.whatiread.data.ISBN13; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import android.app.ActionBar; import android.app.ActionBar.Tab; import android.app.ActionBar.TabListener; import android.app.AlertDialog; import android.app.FragmentTransaction; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.Menu; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; public class MainActivity extends FragmentActivity { private static class PageAdapter extends FragmentPagerAdapter { public PageAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int item) { switch (item) { case 0: return new AddOrCheckFragment(); case 1: return new BrowseFragment(); } return null; } @Override public int getCount() { return 2; } } private Collection<AsyncTask<?, ?, ?>> backgroundTasks = new HashSet<AsyncTask<?, ?, ?>>(); private ViewPager viewPager; private PageAdapter pageAdapter; private ActionBar actionBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewPager = (ViewPager) findViewById(R.id.pager); pageAdapter = new PageAdapter(getSupportFragmentManager()); actionBar = getActionBar(); viewPager.setAdapter(pageAdapter); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setHomeButtonEnabled(false); TabListener tabListener = new TabListener() { @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) {} @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { - actionBar.setSelectedNavigationItem(tab.getPosition()); + viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) {} }; OnPageChangeListener pageChangeListener = new OnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) {} @Override public void onPageScrollStateChanged(int arg0) {} }; String[] titles = { getString(R.string.fragment_title_register), getString(R.string.fragment_title_browse) }; for (String name : titles) { actionBar.addTab(actionBar.newTab().setText(name).setTabListener(tabListener)); } viewPager.setOnPageChangeListener(pageChangeListener); } @Override protected void onDestroy() { for (AsyncTask<?, ?, ?> temp : backgroundTasks) { temp.cancel(false); } super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); menu.add(R.string.action_about).setOnMenuItemClickListener( new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { new AlertDialog.Builder(MainActivity.this) .setMessage(R.string.alpha) .setNeutralButton(R.string.action_ok, null) .show(); return true; } }); return true; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { IntentResult scanResult = IntentIntegrator.parseActivityResult( requestCode, resultCode, data); if (scanResult != null) { String code = scanResult.getContents(); ISBN13 isbn = ISBN13.parse(code); if (isbn != null) { lookupISBN(isbn); } } } void lookupISBN(ISBN13 isbn) { final ProgressDialog progressDialog = ProgressDialog.show(this, getString(R.string.progress_pleaseWait), getString(R.string.progress_initial)); AsyncCallbackReceiver<BookInfo, String> tempCallback = new AsyncCallbackReceiver<BookInfo, String>() { @Override public void onAsyncComplete(BookInfo anObject) { if (progressDialog.isShowing()) { progressDialog.dismiss(); } if (anObject != null) { displayBookInfo(anObject, true); } } @Override public void onProgressReport(String... someProgress) { progressDialog.setMessage(someProgress[0]); } }; BookISBNLookup lookup = new BookISBNLookup(tempCallback, this); lookup.execute(isbn); } void displayBookInfo(BookInfo anObject, boolean warnForExisting) { Intent tempIntent = new Intent(this, DisplayBookActivity.class); tempIntent.putExtra(DisplayBookActivity.BOOK_INFO_VARIABLE, anObject); tempIntent.putExtra(DisplayBookActivity.WARN_FOR_READ_BOOKS_VARIABLE, warnForExisting); startActivity(tempIntent); } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewPager = (ViewPager) findViewById(R.id.pager); pageAdapter = new PageAdapter(getSupportFragmentManager()); actionBar = getActionBar(); viewPager.setAdapter(pageAdapter); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setHomeButtonEnabled(false); TabListener tabListener = new TabListener() { @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) {} @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { actionBar.setSelectedNavigationItem(tab.getPosition()); } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) {} }; OnPageChangeListener pageChangeListener = new OnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) {} @Override public void onPageScrollStateChanged(int arg0) {} }; String[] titles = { getString(R.string.fragment_title_register), getString(R.string.fragment_title_browse) }; for (String name : titles) { actionBar.addTab(actionBar.newTab().setText(name).setTabListener(tabListener)); } viewPager.setOnPageChangeListener(pageChangeListener); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewPager = (ViewPager) findViewById(R.id.pager); pageAdapter = new PageAdapter(getSupportFragmentManager()); actionBar = getActionBar(); viewPager.setAdapter(pageAdapter); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setHomeButtonEnabled(false); TabListener tabListener = new TabListener() { @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) {} @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) {} }; OnPageChangeListener pageChangeListener = new OnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) {} @Override public void onPageScrollStateChanged(int arg0) {} }; String[] titles = { getString(R.string.fragment_title_register), getString(R.string.fragment_title_browse) }; for (String name : titles) { actionBar.addTab(actionBar.newTab().setText(name).setTabListener(tabListener)); } viewPager.setOnPageChangeListener(pageChangeListener); }
diff --git a/src/java/com/twitter/elephantbird/mapreduce/input/LzoBinaryB64LineRecordReader.java b/src/java/com/twitter/elephantbird/mapreduce/input/LzoBinaryB64LineRecordReader.java index 57914399..038360a0 100644 --- a/src/java/com/twitter/elephantbird/mapreduce/input/LzoBinaryB64LineRecordReader.java +++ b/src/java/com/twitter/elephantbird/mapreduce/input/LzoBinaryB64LineRecordReader.java @@ -1,146 +1,146 @@ package com.twitter.elephantbird.mapreduce.input; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import com.twitter.elephantbird.mapreduce.io.BinaryConverter; import com.twitter.elephantbird.mapreduce.io.BinaryWritable; import com.twitter.elephantbird.util.Codecs; import com.twitter.elephantbird.util.HadoopUtils; import com.twitter.elephantbird.util.TypeRef; import org.apache.commons.codec.binary.Base64; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.util.LineReader; /** * Reads line from an lzo compressed text file, base64 decodes it, and then * deserializes that into the templatized object. * * <p> * A small fraction of bad records are tolerated. See {@link LzoRecordReader} * for more information on error handling. */ public class LzoBinaryB64LineRecordReader<M, W extends BinaryWritable<M>> extends LzoRecordReader<LongWritable, W> { private LineReader lineReader_; private final Text line_ = new Text(); private final LongWritable key_ = new LongWritable(); private final W value_; private TypeRef<M> typeRef_; private final Base64 base64_ = Codecs.createStandardBase64(); private final BinaryConverter<M> converter_; private Counter linesReadCounter; private Counter emptyLinesCounter; private Counter recordsReadCounter; private Counter recordErrorsCounter; protected LzoBinaryB64LineRecordReader(TypeRef<M> typeRef, W protobufWritable, BinaryConverter<M> protoConverter) { typeRef_ = typeRef; converter_ = protoConverter; value_ = protobufWritable; } @Override public synchronized void close() throws IOException { if (lineReader_ != null) { lineReader_.close(); } } @Override public LongWritable getCurrentKey() throws IOException, InterruptedException { return key_; } @Override public W getCurrentValue() throws IOException, InterruptedException { return value_; } @Override protected void createInputReader(InputStream input, Configuration conf) throws IOException { lineReader_ = new LineReader(input, conf); } @Override public void initialize(InputSplit genericSplit, TaskAttemptContext context) throws IOException, InterruptedException { String group = "LzoB64Lines of " + typeRef_.getRawClass().getName(); linesReadCounter = HadoopUtils.getCounter(context, group, "Lines Read"); recordsReadCounter = HadoopUtils.getCounter(context, group, "Records Read"); recordErrorsCounter = HadoopUtils.getCounter(context, group, "Errors"); emptyLinesCounter = HadoopUtils.getCounter(context, group, "Empty Lines"); super.initialize(genericSplit, context); } @Override protected void skipToNextSyncPoint(boolean atFirstRecord) throws IOException { if (!atFirstRecord) { lineReader_.readLine(new Text()); } } /** * Read the next key, value pair. * <p> * A small fraction of bad records in input are tolerated. * See {@link LzoRecordReader} for more information on error handling. * * @return true if a key/value pair was read * @throws IOException * @throws InterruptedException */ @Override public boolean nextKeyValue() throws IOException, InterruptedException { // Since the lzop codec reads everything in lzo blocks, we can't stop if pos == end. // Instead we wait for the next block to be read in, when pos will be > end. while (pos_ <= end_) { key_.set(pos_); int newSize = lineReader_.readLine(line_); if (newSize == 0) { return false; } linesReadCounter.increment(1); pos_ = getLzoFilePos(); - if (line_.equals("\n")) { + if (line_.getLength() == 0 || line_.charAt(0) == '\n') { emptyLinesCounter.increment(1); continue; } M protoValue = null; errorTracker.incRecords(); Throwable decodeException = null; try { byte[] lineBytes = Arrays.copyOf(line_.getBytes(), line_.getLength()); protoValue = converter_.fromBytes(base64_.decode(lineBytes)); } catch(Throwable t) { decodeException = t; } if (protoValue == null) { recordErrorsCounter.increment(1); errorTracker.incErrors(decodeException); continue; } recordsReadCounter.increment(1); value_.set(protoValue); return true; } return false; } }
true
true
public boolean nextKeyValue() throws IOException, InterruptedException { // Since the lzop codec reads everything in lzo blocks, we can't stop if pos == end. // Instead we wait for the next block to be read in, when pos will be > end. while (pos_ <= end_) { key_.set(pos_); int newSize = lineReader_.readLine(line_); if (newSize == 0) { return false; } linesReadCounter.increment(1); pos_ = getLzoFilePos(); if (line_.equals("\n")) { emptyLinesCounter.increment(1); continue; } M protoValue = null; errorTracker.incRecords(); Throwable decodeException = null; try { byte[] lineBytes = Arrays.copyOf(line_.getBytes(), line_.getLength()); protoValue = converter_.fromBytes(base64_.decode(lineBytes)); } catch(Throwable t) { decodeException = t; } if (protoValue == null) { recordErrorsCounter.increment(1); errorTracker.incErrors(decodeException); continue; } recordsReadCounter.increment(1); value_.set(protoValue); return true; } return false; }
public boolean nextKeyValue() throws IOException, InterruptedException { // Since the lzop codec reads everything in lzo blocks, we can't stop if pos == end. // Instead we wait for the next block to be read in, when pos will be > end. while (pos_ <= end_) { key_.set(pos_); int newSize = lineReader_.readLine(line_); if (newSize == 0) { return false; } linesReadCounter.increment(1); pos_ = getLzoFilePos(); if (line_.getLength() == 0 || line_.charAt(0) == '\n') { emptyLinesCounter.increment(1); continue; } M protoValue = null; errorTracker.incRecords(); Throwable decodeException = null; try { byte[] lineBytes = Arrays.copyOf(line_.getBytes(), line_.getLength()); protoValue = converter_.fromBytes(base64_.decode(lineBytes)); } catch(Throwable t) { decodeException = t; } if (protoValue == null) { recordErrorsCounter.increment(1); errorTracker.incErrors(decodeException); continue; } recordsReadCounter.increment(1); value_.set(protoValue); return true; } return false; }
diff --git a/TDI/src/controller/BigLogic.java b/TDI/src/controller/BigLogic.java index 25ae878..cf6a227 100644 --- a/TDI/src/controller/BigLogic.java +++ b/TDI/src/controller/BigLogic.java @@ -1,411 +1,415 @@ package controller; import java.util.ArrayList; import java.util.Collections; import java.util.Timer; import java.util.TimerTask; import model.ConfigLoader; import model.Server; import view.Icon; import view.TDI; import view.TDIDialog; import view.Wallpaper; /** * Implements Runnable interface. Is Master, is big. */ public class BigLogic implements Runnable { public ArrayList<Icon> icons; public ArrayList<TDI> tdis; private Server server; /** * counter for scaling */ private int scaleCount=0; private int scaleCount2=0; /** * times(1 = 100ms) to wait for scaling */ private int waitTime=5; /** * The wallpaper */ private Wallpaper wallpaper; /** * The commands that have to be executed. */ public ArrayList<TDI> commands; /** * Lädt Dialog und Desktop configuration * * @param args */ public static void main(String[] args) { BigLogic bl = new BigLogic(); } /** * The run method that is overridden */ public void run() { while (true) { if (commands.size() > 0) { if (tdis.contains(commands.get(0))) { TDI tdi = tdis.get(tdis.indexOf(commands.get(0))); TDI command = commands.get(0); float[] movParam = new float[3]; TDI windFocused=null; TDI taskFocused=null; if (tdi.getPosition() != command.getPosition()) { //CASE POSITION if (tdi.getPosition()[0] != command.getPosition()[0] || tdi.getPosition()[1] != command.getPosition()[1]) // if x or y axis changed { //SZENARIO A DM if(tdi.getState()=="desktop") // is in Desktop Mode == kein TDI in Taskbar == kein Fenster offen { if(tdi.getLocked() == false) { if(PosInTaskbar(command.getPosition()[0],command.getPosition()[1]) == false)//ist die neue Position in Taskbar? { // TDI für Icons zuständig // neu berechenen der zugehörigen Icons } else // neue pos in taskbar => setzen des Tdi in taskbar mode öffen von program { tdi.setState("taskbar"); ProgramHandler.openProgram(tdi.getIcons().get(0)); //open active icon //Vibrate(); //500ms //setLedRed(); tdi.setPosition(0, 0, 0); // linke Ecke der Taskbar for(int x=2,y=10; x < tdis.size() ;x++) // set evry other tdi in the middle of the desk { tdis.get(tdis.indexOf(commands.get(x))).setPosition(0, 0, 0+y); // irgendwo am Rand des Tisches (+y damit sie nicht aufeinander fahren) tdis.get(tdis.indexOf(commands.get(x))).setState("default"); // //setLedGreen(); //set one tdi in window mode - position = middle of the desk tdis.get(tdis.indexOf(commands.get(1))).setState("window"); tdis.get(tdis.indexOf(commands.get(1))).setPosition(0, 0, 0); } } } } if(tdi.getState()=="taskbar") { if(ProgramHandler.getRunningPrograms().size()>0) //if programs are open (at least 1) { if(PosInTaskbar(command.getPosition()[0],command.getPosition()[1])) // neue pos immer noch in taskbar { tdi.setPosition(command.getPosition()[0], command.getPosition()[1], tdi.getPosition()[2]); } else // neue pos außerhalb der taskbar { for(TDI t: tdis) // find out if any other TDI has focused a window { if(t.getState()=="window") windFocused=t; } if(windFocused != null) { if(StartScaleMode(tdi,windFocused)) { scaleCount2=scaleCount2+1; if(scaleCount2==waitTime) { scaleCount2=0; // skaliermodus TDI repräsentiert untere linke Ecke des Fensters taskFocused.setPosition(0, 0, 0); tdi.setIsScale(true); windFocused.setIsScale(true); float width=windFocused.getPosition()[0]-tdi.getPosition()[0]; float height=windFocused.getPosition()[1]-tdi.getPosition()[1]; ProgramHandler.resizeProgram(width, height); } else { tdi.setPosition(tdis.indexOf(commands.get(0).getPosition()[0]), tdis.indexOf(commands.get(0).getPosition()[1]), tdis.indexOf(commands.get(0).getPosition()[2])); } } } else { tdi.setPosition(command.getPosition()[0], command.getPosition()[1], tdi.getPosition()[2]); } } } else { for(int x=0; x < tdis.size() ;x++) // set evry tdi in desktop mode cause no programs are open { tdis.get(tdis.indexOf(commands.get(x))).setState("desktop"); //? tdis.get(tdis.indexOf(commands.get(x))).setPosition(1, 1, 1);// wohin?? } } } if(tdi.getState()=="window") { for(TDI t: tdis) // find out taskbar tdi { if(t.getState()=="taskbar") taskFocused=t; } // taskbar TDI in nähe des aktuellen if(StartScaleMode(taskFocused, tdi)) { scaleCount=scaleCount+1; if(scaleCount==waitTime) { scaleCount=0; // skaliermodus TDI repräsentiert obere linke Ecke des Fensters tdi.setPosition(0, 0, 0); // TODO window TDI repräsentiert obere rechte Ecke des Fensters taskFocused.setPosition(0, 0, 0); tdi.setIsScale(true); taskFocused.setIsScale(true); float width=taskFocused.getPosition()[0]-tdi.getPosition()[0]; float height=taskFocused.getPosition()[1]-tdi.getPosition()[1]; ProgramHandler.resizeProgram(width, height); } else { tdi.setPosition(tdis.indexOf(commands.get(0).getPosition()[0]), tdis.indexOf(commands.get(0).getPosition()[1]), tdis.indexOf(commands.get(0).getPosition()[2])); } } else { tdi.setPosition(command.getPosition()[0], command.getPosition()[1], tdi.getPosition()[2]); //tdi.getIcons().get(0).setPosition(); new position of program window } } if(tdi.getState()=="inapp") { } } } //neigen //TODO change rotation => 1 wert drehen 2 werte neigen //welcher der Werte ist neigen (jeweils positiv verändert / negativ verändert) = 4 werte if (tdi.getRotation() != command.getRotation()) { if(tdi.getState()=="desktop") { //nach rechts neigen if (tdi.getRotation()[1] != command.getRotation()[1]) tdi.toggleLock(); //tdi.toggleGreenLED(); } if(tdi.getState()=="window") { //nach oben if (tdi.getRotation()[0] != command.getRotation()[0]) { ProgramHandler.toggleMaximization(); if(ProgramHandler.getNonMinimized()==0) { tdi.setState("desktop"); tdi.setPosition(1, 1, 1); splitIcons(); } } //nach links neigen if(tdi.getRotation()[3]!=command.getRotation()[3]) { ProgramHandler.closeProgram(); tdi.getIcons().remove(0); } // TDI nach unten neigen if (tdi.getRotation()[2] != command.getRotation()[2]) { ProgramHandler.minimize(); //TODO When still focused, move TDI when not for icons if(ProgramHandler.isDesktopMode()) { tdi.setState("desktop"); tdi.setPosition(1, 1, 1); splitIcons(); } else { tdi.setPosition(1, 1, 1); //TODO GO to location of window }; } } if(tdi.getState()=="taskbar") { /* TDI nach oben neigen Alle Fenster werden wiederhergestellt */ //nach oben if (tdi.getRotation()[0] != command.getRotation()[0]) { ProgramHandler.restoreAllPrograms(); if(ProgramHandler.isDesktopMode()) { if(tdis.get(1).getState()!="taskbar") { tdis.get(1).setState("window"); tdis.get(1).setPosition(1, 1, 1); // to maximised window } else { tdis.get(2).setState("window"); tdis.get(1).setPosition(1, 1, 1); // to maximised window } } else { for(TDI t:tdis) { if(t.getState()=="window") { t.setPosition(1, 1, 1); // to maximised window } } } } //nach links/rechts neigen if(tdi.getRotation()[3]!=command.getRotation()[3]) { ProgramHandler.closeAllPrograms(); for(TDI t:tdis) { t.setState("desktop"); } } // TDI nach unten neigen if (tdi.getRotation()[2] != command.getRotation()[2]) { ProgramHandler.minimizeAllPrograms(); for(TDI t:tdis) { if(t.getState()=="window") { t.setState("desktop"); tdi.setPosition(1, 1, 1); splitIcons(); } } } } } // drehen if(tdi.getRotation() != command.getRotation()) { if(tdi.getState()=="taskbar") { //nicht im Skaliermodus if(tdi.getIsScale()==false) { //nach links Das vorherige Fenster in der Taskleiste wird fokussiert if(tdi.getRotation()[0] > command.getRotation()[0]) { tdi.setRotation(command.getRotation()); tdi.getIcons().set(0, tdi.getIcons().get(tdi.getIcons().size())); } //nach rechts Das nächste Fenster in der Taskleiste wird fokussiert if(tdi.getRotation()[0] < command.getRotation()[0]) { tdi.setRotation(command.getRotation()); tdi.getIcons().set(0, tdi.getIcons().get(1)); } } } if(tdi.getState()=="desktop") { //nach links Das vorherige Icon, wofür das TDI zuständig ist wird ausgewählt if(tdi.getRotation()[0] > command.getRotation()[0]) { tdi.setRotation(command.getRotation()); tdi.getIcons().set(0, tdi.getIcons().get(tdi.getIcons().size())); } //nach rechts Das nächste Icon, wofür das TDI zuständig ist wird ausgewählt if(tdi.getRotation()[0] < command.getRotation()[0]) { tdi.setRotation(command.getRotation()); tdi.getIcons().set(0, tdi.getIcons().get(1)); } } if(tdi.getState()=="inapp") { - // depends ?! + //nach rechts neigen + if(tdi.getRotation()[0] > command.getRotation()[0]) + { + tdi.setState("window"); + } } } } } } } /** * * @param command */ public void addCommand(TDI command) { commands.add(command); } /** * checks if givenPos is in taskbar * @return */ private boolean PosInTaskbar(float x, float y) { return true; } /** * checks if a taskbar TDI and a window TDI are near enough to start the scale mode */ private boolean StartScaleMode(TDI t1, TDI t2) { int range = 5; if(t1.getPosition()[0] <= t2.getPosition()[0]+range && t1.getPosition()[0] >= t2.getPosition()[0]-range || t1.getPosition()[1] <= t2.getPosition()[1]+range && t1.getPosition()[1] >= t2.getPosition()[1]-range) return true; if(t2.getPosition()[0] <= t1.getPosition()[0]+range && t2.getPosition()[0] >= t1.getPosition()[0]-range || t2.getPosition()[1] <= t1.getPosition()[1]+range && t2.getPosition()[1] >= t1.getPosition()[1]-range) return true; else return false; } public BigLogic() { ConfigLoader cl = new ConfigLoader(); // TDIDialog td = new TDIDialog(cl.getPlugins()); icons = cl.loadIcons(); Collections.sort(icons); // wallpaper.setBackground(cl.loadWallpaper()); // wallpaper.setResolution(cl.loadScreensize()); server = new Server(); tdis = server.fullPose(); splitIcons(); Timer mo = new Timer(); mo.scheduleAtFixedRate(new TimerTask() { @Override public void run() { ArrayList<TDI> tdis = server.fullPose(); for (TDI t : tdis) { commands.add(t); } } }, 0, 500); } public void splitIcons() { float f = icons.size() / tdis.size(); if (icons.size() % tdis.size() == 0) { for (TDI t : tdis) { int f1 = (int) f; int fromIndex = 0; t.setIcons(icons.subList(fromIndex, fromIndex += f1)); } } } }
true
true
public void run() { while (true) { if (commands.size() > 0) { if (tdis.contains(commands.get(0))) { TDI tdi = tdis.get(tdis.indexOf(commands.get(0))); TDI command = commands.get(0); float[] movParam = new float[3]; TDI windFocused=null; TDI taskFocused=null; if (tdi.getPosition() != command.getPosition()) { //CASE POSITION if (tdi.getPosition()[0] != command.getPosition()[0] || tdi.getPosition()[1] != command.getPosition()[1]) // if x or y axis changed { //SZENARIO A DM if(tdi.getState()=="desktop") // is in Desktop Mode == kein TDI in Taskbar == kein Fenster offen { if(tdi.getLocked() == false) { if(PosInTaskbar(command.getPosition()[0],command.getPosition()[1]) == false)//ist die neue Position in Taskbar? { // TDI für Icons zuständig // neu berechenen der zugehörigen Icons } else // neue pos in taskbar => setzen des Tdi in taskbar mode öffen von program { tdi.setState("taskbar"); ProgramHandler.openProgram(tdi.getIcons().get(0)); //open active icon //Vibrate(); //500ms //setLedRed(); tdi.setPosition(0, 0, 0); // linke Ecke der Taskbar for(int x=2,y=10; x < tdis.size() ;x++) // set evry other tdi in the middle of the desk { tdis.get(tdis.indexOf(commands.get(x))).setPosition(0, 0, 0+y); // irgendwo am Rand des Tisches (+y damit sie nicht aufeinander fahren) tdis.get(tdis.indexOf(commands.get(x))).setState("default"); // //setLedGreen(); //set one tdi in window mode - position = middle of the desk tdis.get(tdis.indexOf(commands.get(1))).setState("window"); tdis.get(tdis.indexOf(commands.get(1))).setPosition(0, 0, 0); } } } } if(tdi.getState()=="taskbar") { if(ProgramHandler.getRunningPrograms().size()>0) //if programs are open (at least 1) { if(PosInTaskbar(command.getPosition()[0],command.getPosition()[1])) // neue pos immer noch in taskbar { tdi.setPosition(command.getPosition()[0], command.getPosition()[1], tdi.getPosition()[2]); } else // neue pos außerhalb der taskbar { for(TDI t: tdis) // find out if any other TDI has focused a window { if(t.getState()=="window") windFocused=t; } if(windFocused != null) { if(StartScaleMode(tdi,windFocused)) { scaleCount2=scaleCount2+1; if(scaleCount2==waitTime) { scaleCount2=0; // skaliermodus TDI repräsentiert untere linke Ecke des Fensters taskFocused.setPosition(0, 0, 0); tdi.setIsScale(true); windFocused.setIsScale(true); float width=windFocused.getPosition()[0]-tdi.getPosition()[0]; float height=windFocused.getPosition()[1]-tdi.getPosition()[1]; ProgramHandler.resizeProgram(width, height); } else { tdi.setPosition(tdis.indexOf(commands.get(0).getPosition()[0]), tdis.indexOf(commands.get(0).getPosition()[1]), tdis.indexOf(commands.get(0).getPosition()[2])); } } } else { tdi.setPosition(command.getPosition()[0], command.getPosition()[1], tdi.getPosition()[2]); } } } else { for(int x=0; x < tdis.size() ;x++) // set evry tdi in desktop mode cause no programs are open { tdis.get(tdis.indexOf(commands.get(x))).setState("desktop"); //? tdis.get(tdis.indexOf(commands.get(x))).setPosition(1, 1, 1);// wohin?? } } } if(tdi.getState()=="window") { for(TDI t: tdis) // find out taskbar tdi { if(t.getState()=="taskbar") taskFocused=t; } // taskbar TDI in nähe des aktuellen if(StartScaleMode(taskFocused, tdi)) { scaleCount=scaleCount+1; if(scaleCount==waitTime) { scaleCount=0; // skaliermodus TDI repräsentiert obere linke Ecke des Fensters tdi.setPosition(0, 0, 0); // TODO window TDI repräsentiert obere rechte Ecke des Fensters taskFocused.setPosition(0, 0, 0); tdi.setIsScale(true); taskFocused.setIsScale(true); float width=taskFocused.getPosition()[0]-tdi.getPosition()[0]; float height=taskFocused.getPosition()[1]-tdi.getPosition()[1]; ProgramHandler.resizeProgram(width, height); } else { tdi.setPosition(tdis.indexOf(commands.get(0).getPosition()[0]), tdis.indexOf(commands.get(0).getPosition()[1]), tdis.indexOf(commands.get(0).getPosition()[2])); } } else { tdi.setPosition(command.getPosition()[0], command.getPosition()[1], tdi.getPosition()[2]); //tdi.getIcons().get(0).setPosition(); new position of program window } } if(tdi.getState()=="inapp") { } } } //neigen //TODO change rotation => 1 wert drehen 2 werte neigen //welcher der Werte ist neigen (jeweils positiv verändert / negativ verändert) = 4 werte if (tdi.getRotation() != command.getRotation()) { if(tdi.getState()=="desktop") { //nach rechts neigen if (tdi.getRotation()[1] != command.getRotation()[1]) tdi.toggleLock(); //tdi.toggleGreenLED(); } if(tdi.getState()=="window") { //nach oben if (tdi.getRotation()[0] != command.getRotation()[0]) { ProgramHandler.toggleMaximization(); if(ProgramHandler.getNonMinimized()==0) { tdi.setState("desktop"); tdi.setPosition(1, 1, 1); splitIcons(); } } //nach links neigen if(tdi.getRotation()[3]!=command.getRotation()[3]) { ProgramHandler.closeProgram(); tdi.getIcons().remove(0); } // TDI nach unten neigen if (tdi.getRotation()[2] != command.getRotation()[2]) { ProgramHandler.minimize(); //TODO When still focused, move TDI when not for icons if(ProgramHandler.isDesktopMode()) { tdi.setState("desktop"); tdi.setPosition(1, 1, 1); splitIcons(); } else { tdi.setPosition(1, 1, 1); //TODO GO to location of window }; } } if(tdi.getState()=="taskbar") { /* TDI nach oben neigen Alle Fenster werden wiederhergestellt */ //nach oben if (tdi.getRotation()[0] != command.getRotation()[0]) { ProgramHandler.restoreAllPrograms(); if(ProgramHandler.isDesktopMode()) { if(tdis.get(1).getState()!="taskbar") { tdis.get(1).setState("window"); tdis.get(1).setPosition(1, 1, 1); // to maximised window } else { tdis.get(2).setState("window"); tdis.get(1).setPosition(1, 1, 1); // to maximised window } } else { for(TDI t:tdis) { if(t.getState()=="window") { t.setPosition(1, 1, 1); // to maximised window } } } } //nach links/rechts neigen if(tdi.getRotation()[3]!=command.getRotation()[3]) { ProgramHandler.closeAllPrograms(); for(TDI t:tdis) { t.setState("desktop"); } } // TDI nach unten neigen if (tdi.getRotation()[2] != command.getRotation()[2]) { ProgramHandler.minimizeAllPrograms(); for(TDI t:tdis) { if(t.getState()=="window") { t.setState("desktop"); tdi.setPosition(1, 1, 1); splitIcons(); } } } } } // drehen if(tdi.getRotation() != command.getRotation()) { if(tdi.getState()=="taskbar") { //nicht im Skaliermodus if(tdi.getIsScale()==false) { //nach links Das vorherige Fenster in der Taskleiste wird fokussiert if(tdi.getRotation()[0] > command.getRotation()[0]) { tdi.setRotation(command.getRotation()); tdi.getIcons().set(0, tdi.getIcons().get(tdi.getIcons().size())); } //nach rechts Das nächste Fenster in der Taskleiste wird fokussiert if(tdi.getRotation()[0] < command.getRotation()[0]) { tdi.setRotation(command.getRotation()); tdi.getIcons().set(0, tdi.getIcons().get(1)); } } } if(tdi.getState()=="desktop") { //nach links Das vorherige Icon, wofür das TDI zuständig ist wird ausgewählt if(tdi.getRotation()[0] > command.getRotation()[0]) { tdi.setRotation(command.getRotation()); tdi.getIcons().set(0, tdi.getIcons().get(tdi.getIcons().size())); } //nach rechts Das nächste Icon, wofür das TDI zuständig ist wird ausgewählt if(tdi.getRotation()[0] < command.getRotation()[0]) { tdi.setRotation(command.getRotation()); tdi.getIcons().set(0, tdi.getIcons().get(1)); } } if(tdi.getState()=="inapp") { // depends ?! } } } } } }
public void run() { while (true) { if (commands.size() > 0) { if (tdis.contains(commands.get(0))) { TDI tdi = tdis.get(tdis.indexOf(commands.get(0))); TDI command = commands.get(0); float[] movParam = new float[3]; TDI windFocused=null; TDI taskFocused=null; if (tdi.getPosition() != command.getPosition()) { //CASE POSITION if (tdi.getPosition()[0] != command.getPosition()[0] || tdi.getPosition()[1] != command.getPosition()[1]) // if x or y axis changed { //SZENARIO A DM if(tdi.getState()=="desktop") // is in Desktop Mode == kein TDI in Taskbar == kein Fenster offen { if(tdi.getLocked() == false) { if(PosInTaskbar(command.getPosition()[0],command.getPosition()[1]) == false)//ist die neue Position in Taskbar? { // TDI für Icons zuständig // neu berechenen der zugehörigen Icons } else // neue pos in taskbar => setzen des Tdi in taskbar mode öffen von program { tdi.setState("taskbar"); ProgramHandler.openProgram(tdi.getIcons().get(0)); //open active icon //Vibrate(); //500ms //setLedRed(); tdi.setPosition(0, 0, 0); // linke Ecke der Taskbar for(int x=2,y=10; x < tdis.size() ;x++) // set evry other tdi in the middle of the desk { tdis.get(tdis.indexOf(commands.get(x))).setPosition(0, 0, 0+y); // irgendwo am Rand des Tisches (+y damit sie nicht aufeinander fahren) tdis.get(tdis.indexOf(commands.get(x))).setState("default"); // //setLedGreen(); //set one tdi in window mode - position = middle of the desk tdis.get(tdis.indexOf(commands.get(1))).setState("window"); tdis.get(tdis.indexOf(commands.get(1))).setPosition(0, 0, 0); } } } } if(tdi.getState()=="taskbar") { if(ProgramHandler.getRunningPrograms().size()>0) //if programs are open (at least 1) { if(PosInTaskbar(command.getPosition()[0],command.getPosition()[1])) // neue pos immer noch in taskbar { tdi.setPosition(command.getPosition()[0], command.getPosition()[1], tdi.getPosition()[2]); } else // neue pos außerhalb der taskbar { for(TDI t: tdis) // find out if any other TDI has focused a window { if(t.getState()=="window") windFocused=t; } if(windFocused != null) { if(StartScaleMode(tdi,windFocused)) { scaleCount2=scaleCount2+1; if(scaleCount2==waitTime) { scaleCount2=0; // skaliermodus TDI repräsentiert untere linke Ecke des Fensters taskFocused.setPosition(0, 0, 0); tdi.setIsScale(true); windFocused.setIsScale(true); float width=windFocused.getPosition()[0]-tdi.getPosition()[0]; float height=windFocused.getPosition()[1]-tdi.getPosition()[1]; ProgramHandler.resizeProgram(width, height); } else { tdi.setPosition(tdis.indexOf(commands.get(0).getPosition()[0]), tdis.indexOf(commands.get(0).getPosition()[1]), tdis.indexOf(commands.get(0).getPosition()[2])); } } } else { tdi.setPosition(command.getPosition()[0], command.getPosition()[1], tdi.getPosition()[2]); } } } else { for(int x=0; x < tdis.size() ;x++) // set evry tdi in desktop mode cause no programs are open { tdis.get(tdis.indexOf(commands.get(x))).setState("desktop"); //? tdis.get(tdis.indexOf(commands.get(x))).setPosition(1, 1, 1);// wohin?? } } } if(tdi.getState()=="window") { for(TDI t: tdis) // find out taskbar tdi { if(t.getState()=="taskbar") taskFocused=t; } // taskbar TDI in nähe des aktuellen if(StartScaleMode(taskFocused, tdi)) { scaleCount=scaleCount+1; if(scaleCount==waitTime) { scaleCount=0; // skaliermodus TDI repräsentiert obere linke Ecke des Fensters tdi.setPosition(0, 0, 0); // TODO window TDI repräsentiert obere rechte Ecke des Fensters taskFocused.setPosition(0, 0, 0); tdi.setIsScale(true); taskFocused.setIsScale(true); float width=taskFocused.getPosition()[0]-tdi.getPosition()[0]; float height=taskFocused.getPosition()[1]-tdi.getPosition()[1]; ProgramHandler.resizeProgram(width, height); } else { tdi.setPosition(tdis.indexOf(commands.get(0).getPosition()[0]), tdis.indexOf(commands.get(0).getPosition()[1]), tdis.indexOf(commands.get(0).getPosition()[2])); } } else { tdi.setPosition(command.getPosition()[0], command.getPosition()[1], tdi.getPosition()[2]); //tdi.getIcons().get(0).setPosition(); new position of program window } } if(tdi.getState()=="inapp") { } } } //neigen //TODO change rotation => 1 wert drehen 2 werte neigen //welcher der Werte ist neigen (jeweils positiv verändert / negativ verändert) = 4 werte if (tdi.getRotation() != command.getRotation()) { if(tdi.getState()=="desktop") { //nach rechts neigen if (tdi.getRotation()[1] != command.getRotation()[1]) tdi.toggleLock(); //tdi.toggleGreenLED(); } if(tdi.getState()=="window") { //nach oben if (tdi.getRotation()[0] != command.getRotation()[0]) { ProgramHandler.toggleMaximization(); if(ProgramHandler.getNonMinimized()==0) { tdi.setState("desktop"); tdi.setPosition(1, 1, 1); splitIcons(); } } //nach links neigen if(tdi.getRotation()[3]!=command.getRotation()[3]) { ProgramHandler.closeProgram(); tdi.getIcons().remove(0); } // TDI nach unten neigen if (tdi.getRotation()[2] != command.getRotation()[2]) { ProgramHandler.minimize(); //TODO When still focused, move TDI when not for icons if(ProgramHandler.isDesktopMode()) { tdi.setState("desktop"); tdi.setPosition(1, 1, 1); splitIcons(); } else { tdi.setPosition(1, 1, 1); //TODO GO to location of window }; } } if(tdi.getState()=="taskbar") { /* TDI nach oben neigen Alle Fenster werden wiederhergestellt */ //nach oben if (tdi.getRotation()[0] != command.getRotation()[0]) { ProgramHandler.restoreAllPrograms(); if(ProgramHandler.isDesktopMode()) { if(tdis.get(1).getState()!="taskbar") { tdis.get(1).setState("window"); tdis.get(1).setPosition(1, 1, 1); // to maximised window } else { tdis.get(2).setState("window"); tdis.get(1).setPosition(1, 1, 1); // to maximised window } } else { for(TDI t:tdis) { if(t.getState()=="window") { t.setPosition(1, 1, 1); // to maximised window } } } } //nach links/rechts neigen if(tdi.getRotation()[3]!=command.getRotation()[3]) { ProgramHandler.closeAllPrograms(); for(TDI t:tdis) { t.setState("desktop"); } } // TDI nach unten neigen if (tdi.getRotation()[2] != command.getRotation()[2]) { ProgramHandler.minimizeAllPrograms(); for(TDI t:tdis) { if(t.getState()=="window") { t.setState("desktop"); tdi.setPosition(1, 1, 1); splitIcons(); } } } } } // drehen if(tdi.getRotation() != command.getRotation()) { if(tdi.getState()=="taskbar") { //nicht im Skaliermodus if(tdi.getIsScale()==false) { //nach links Das vorherige Fenster in der Taskleiste wird fokussiert if(tdi.getRotation()[0] > command.getRotation()[0]) { tdi.setRotation(command.getRotation()); tdi.getIcons().set(0, tdi.getIcons().get(tdi.getIcons().size())); } //nach rechts Das nächste Fenster in der Taskleiste wird fokussiert if(tdi.getRotation()[0] < command.getRotation()[0]) { tdi.setRotation(command.getRotation()); tdi.getIcons().set(0, tdi.getIcons().get(1)); } } } if(tdi.getState()=="desktop") { //nach links Das vorherige Icon, wofür das TDI zuständig ist wird ausgewählt if(tdi.getRotation()[0] > command.getRotation()[0]) { tdi.setRotation(command.getRotation()); tdi.getIcons().set(0, tdi.getIcons().get(tdi.getIcons().size())); } //nach rechts Das nächste Icon, wofür das TDI zuständig ist wird ausgewählt if(tdi.getRotation()[0] < command.getRotation()[0]) { tdi.setRotation(command.getRotation()); tdi.getIcons().set(0, tdi.getIcons().get(1)); } } if(tdi.getState()=="inapp") { //nach rechts neigen if(tdi.getRotation()[0] > command.getRotation()[0]) { tdi.setState("window"); } } } } } } }
diff --git a/src/com/mareksebera/dilbert/DilbertPreferences.java b/src/com/mareksebera/dilbert/DilbertPreferences.java index b833088..9ab26dc 100644 --- a/src/com/mareksebera/dilbert/DilbertPreferences.java +++ b/src/com/mareksebera/dilbert/DilbertPreferences.java @@ -1,103 +1,104 @@ package com.mareksebera.dilbert; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.joda.time.DateMidnight; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; public class DilbertPreferences { private SharedPreferences preferences; private SharedPreferences.Editor editor; private static final String PREF_CURRENT_DATE = "dilbert_current_date"; private static final String PREF_CURRENT_URL = "dilbert_current_url"; private static final String PREF_HIGH_QUALITY_ENABLED = "dilbert_use_high_quality"; public static final DateTimeFormatter dateFormatter = DateTimeFormat .forPattern("yyyy-MM-dd"); public DilbertPreferences(Context _context) { preferences = PreferenceManager.getDefaultSharedPreferences(_context); editor = preferences.edit(); } public DateMidnight getCurrentDate() { String savedDate = preferences.getString(PREF_CURRENT_DATE, null); if (savedDate == null) return DateMidnight.now(); else return DateMidnight.parse(savedDate, dateFormatter); } public boolean saveCurrentDate(DateMidnight currentDate) { editor.putString(PREF_CURRENT_DATE, currentDate.toString(DilbertPreferences.dateFormatter)); return editor.commit(); } public String getLastUrl() { return preferences.getString(PREF_CURRENT_URL, null); } public boolean isHighQualityOn() { return preferences.getBoolean(PREF_HIGH_QUALITY_ENABLED, true); } public boolean saveCurrentUrl(String date, String s) { editor.putString(PREF_CURRENT_URL, s); editor.putString(date, s); return editor.commit(); } public boolean toggleHighQuality() { return editor.putBoolean(PREF_HIGH_QUALITY_ENABLED, !isHighQualityOn()) .commit(); } public String getCachedUrl(String dateKey) { return preferences.getString(dateKey, null); } public boolean removeCache(DateMidnight currentDate) { return editor.remove( currentDate.toString(DilbertPreferences.dateFormatter)) .commit(); } public boolean isFavorited(DateMidnight currentDay) { return preferences.getBoolean(toFavoritedKey(currentDay), false); } public boolean toggleIsFavorited(DateMidnight currentDay) { boolean newState = !isFavorited(currentDay); editor.putBoolean(toFavoritedKey(currentDay), newState).commit(); return newState; } private String toFavoritedKey(DateMidnight currentDay) { return "favorite_" + currentDay.toString(DilbertPreferences.dateFormatter); } public List<FavoritedItem> getFavoritedItems() { List<FavoritedItem> favorites = new ArrayList<FavoritedItem>(); Map<String, ?> allPreferences = preferences.getAll(); for (String key : allPreferences.keySet()) { - if (key.startsWith("favorite_")) { + if (key.startsWith("favorite_") + && (Boolean) allPreferences.get(key)) { String date = key.replace("favorite_", ""); favorites.add(new FavoritedItem(DateMidnight.parse(date, dateFormatter), (String) allPreferences.get(date))); } } return favorites; } }
true
true
public List<FavoritedItem> getFavoritedItems() { List<FavoritedItem> favorites = new ArrayList<FavoritedItem>(); Map<String, ?> allPreferences = preferences.getAll(); for (String key : allPreferences.keySet()) { if (key.startsWith("favorite_")) { String date = key.replace("favorite_", ""); favorites.add(new FavoritedItem(DateMidnight.parse(date, dateFormatter), (String) allPreferences.get(date))); } } return favorites; }
public List<FavoritedItem> getFavoritedItems() { List<FavoritedItem> favorites = new ArrayList<FavoritedItem>(); Map<String, ?> allPreferences = preferences.getAll(); for (String key : allPreferences.keySet()) { if (key.startsWith("favorite_") && (Boolean) allPreferences.get(key)) { String date = key.replace("favorite_", ""); favorites.add(new FavoritedItem(DateMidnight.parse(date, dateFormatter), (String) allPreferences.get(date))); } } return favorites; }
diff --git a/org.eclipse.imp.pdb.values/src/org/eclipse/imp/pdb/facts/io/ATermReader.java b/org.eclipse.imp.pdb.values/src/org/eclipse/imp/pdb/facts/io/ATermReader.java index 813a28f..9d0535d 100644 --- a/org.eclipse.imp.pdb.values/src/org/eclipse/imp/pdb/facts/io/ATermReader.java +++ b/org.eclipse.imp.pdb.values/src/org/eclipse/imp/pdb/facts/io/ATermReader.java @@ -1,717 +1,717 @@ /******************************************************************************* * Copyright (c) INRIA-LORIA and CWI 2006-2009 * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Jurgen Vinju ([email protected]) - initial API and implementation *******************************************************************************/ package org.eclipse.imp.pdb.facts.io; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Set; import org.eclipse.imp.pdb.facts.IConstructor; import org.eclipse.imp.pdb.facts.IListWriter; import org.eclipse.imp.pdb.facts.IMapWriter; import org.eclipse.imp.pdb.facts.ISetWriter; import org.eclipse.imp.pdb.facts.ITuple; import org.eclipse.imp.pdb.facts.IValue; import org.eclipse.imp.pdb.facts.IValueFactory; import org.eclipse.imp.pdb.facts.exceptions.FactParseError; import org.eclipse.imp.pdb.facts.exceptions.IllegalOperationException; import org.eclipse.imp.pdb.facts.exceptions.UndeclaredAbstractDataTypeException; import org.eclipse.imp.pdb.facts.type.Type; import org.eclipse.imp.pdb.facts.type.TypeFactory; import org.eclipse.imp.pdb.facts.type.TypeStore; // TODO: add support for values of type Value, for this we need overloading resolving public class ATermReader extends AbstractReader { private IValueFactory vf; private TypeFactory tf = TypeFactory.getInstance(); private TypeStore ts; public IValue read(IValueFactory factory, TypeStore store, Type type, InputStream stream) throws FactParseError, IOException { this.vf = factory; this.ts = store; int firstToken; do { firstToken = stream.read(); if (firstToken == -1) { throw new IOException("Premature EOF."); } } while (Character.isWhitespace((char) firstToken)); char typeByte = (char) firstToken; if (typeByte == '!') { SharingStream sreader = new SharingStream(stream); sreader.initializeSharing(); sreader.readSkippingWS(); return parse(sreader, type); } else if (typeByte == '?') { throw new UnsupportedOperationException("nyi"); } else if (Character.isLetterOrDigit(typeByte) || typeByte == '_' || typeByte == '[' || typeByte == '-') { SharingStream sreader = new SharingStream(stream); sreader.last_char = typeByte; return parse(sreader, type); } else { throw new RuntimeException("nyi"); } } // TODO add support for anonymous constructors (is already done for the parseNumber case) private IValue parse(SharingStream reader, Type expected) throws IOException { IValue result; int start, end; start = reader.getPosition(); switch (reader.getLastChar()) { case -1: throw new FactParseError("premature EOF encountered.", start); case '#': return parseAbbrev(reader); case '[': result = parseList(reader, expected); break; case '<': throw new FactParseError("Placeholders are not supported", start); case '"': result = parseString(reader, expected); break; case '(': result = parseTuple(reader, expected); break; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': result = parseNumber(reader, expected); break; default: result = parseAppl(reader, expected); } if (reader.getLastChar() == '{') { result = parseAnnotations(reader, result); } end = reader.getPosition(); reader.storeNextTerm(result, end - start); return result; } private IValue parseAnnotations(SharingStream reader, IValue result) throws IOException { if (reader.readSkippingWS() == '}') { reader.readSkippingWS(); } else { result = parseAnnos(reader, result); if (reader.getLastChar() != '}') { throw new FactParseError("'}' expected", reader.getPosition()); } } return result; } private IValue parseAppl(SharingStream reader, Type expected) throws IOException { int c; IValue result; c = reader.getLastChar(); if (Character.isLetter(c)) { String funname = parseId(reader); Type node; if (expected.isAbstractDataType()) { Set<Type> nodes = ts.lookupConstructor(expected, funname); // TODO deal with overloading Iterator<Type> iterator = nodes.iterator(); if (!iterator.hasNext()) { throw new UndeclaredAbstractDataTypeException(expected); } node = iterator.next(); } else { node = expected; } c = reader.skipWS(); if (reader.getLastChar() == '(') { c = reader.readSkippingWS(); if (c == -1) { throw new FactParseError("premature EOF encountered.", reader.getPosition()); } if (reader.getLastChar() == ')') { - result = vf.constructor(node, new IValue[0]); + result = node.make(vf, ts, funname, new IValue[0]); } else { IValue[] list; if (expected.isAbstractDataType()) { list = parseFixedSizeATermsArray(reader, node.getFieldTypes()); } else { list = parseATermsArray(reader, TypeFactory.getInstance().valueType()); } if (reader.getLastChar() != ')') { throw new FactParseError("expected ')' but got '" + (char) reader.getLastChar() + "'", reader.getPosition()); } if (expected.isAbstractDataType()) { - result = node.make(vf, list); + result = node.make(vf, ts, funname, list); } else { - result = node.make(vf, funname, list); + result = node.make(vf, ts, funname, list); } } c = reader.readSkippingWS(); } else { if (node.isAbstractDataType() || node.isConstructorType()) { - result = node.make(vf); + result = node.make(vf, ts); } else { - result = tf.nodeType().make(vf, funname); + result = tf.nodeType().make(vf, ts, funname); } } } else { throw new FactParseError("illegal character: " + (char) reader.getLastChar(), reader.getPosition()); } return result; } private IValue parseTuple(SharingStream reader, Type expected) throws IOException { int c; IValue result; c = reader.readSkippingWS(); if (c == -1) { throw new FactParseError("premature EOF encountered.", reader.getPosition()); } if (reader.getLastChar() == ')') { result = expected.make(vf); } else { IValue[] list = parseFixedSizeATermsArray(reader, expected); if (reader.getLastChar() != ')') { throw new FactParseError("expected ')' but got '" + (char) reader.getLastChar() + "'", reader.getPosition()); } result = expected.make(vf, list); } c = reader.readSkippingWS(); return result; } private IValue parseString(SharingStream reader, Type expected) throws IOException { int c; IValue result; String str = parseStringLiteral(reader); // note that we interpret all strings as strings, not possible function names. // this deviates from the ATerm library. result = expected.make(vf, str); c = reader.readSkippingWS(); if (c == -1) { throw new FactParseError("premature EOF encountered.", reader.getPosition()); } return result; } private IValue parseList(SharingStream reader, Type expected) throws IOException { IValue result; int c; c = reader.readSkippingWS(); if (c == -1) { throw new FactParseError("premature EOF encountered.", reader.getPosition()); } if (c == ']') { c = reader.readSkippingWS(); if (expected.isListType()) { result = expected.make(vf); } else if (expected.isValueType()) { result = tf.listType(tf.valueType()).make(vf); } else { throw new FactParseError("Did not expect a list, rather a " + expected, reader.getPosition()); } } else { result = parseATerms(reader, expected); if (reader.getLastChar() != ']') { throw new FactParseError("expected ']' but got '" + (char) reader.getLastChar() + "'", reader.getPosition()); } c = reader.readSkippingWS(); } return result; } private IValue parseAnnos(SharingStream reader, IValue result) throws IOException { result = parseAnno(reader, result); while (reader.getLastChar() == ',') { reader.readSkippingWS(); result = parseAnno(reader, result); } return result; } private IValue parseAnno(SharingStream reader, IValue result) throws IOException { if (reader.getLastChar() == '[') { int c = reader.readSkippingWS(); if (c == '"') { String key = parseStringLiteral(reader); Type annoType = ts.getAnnotationType(result.getType(), key); if (reader.readSkippingWS() == ',') { reader.readSkippingWS(); IValue value = parse(reader, annoType); if (result.getType().isConstructorType() || result.getType().isAbstractDataType()) { result = ((IConstructor) result).setAnnotation(key, value); } if (reader.getLastChar() != ']') { throw new FactParseError("expected a ] but got a " + reader.getLastChar(), reader.getPosition()); } reader.readSkippingWS(); return result; } throw new FactParseError("expected a comma before the value of the annotation", reader.getPosition()); } throw new FactParseError("expected a label for an annotation", reader.getPosition()); } // no annotations return result; } static private boolean isBase64(int c) { return Character.isLetterOrDigit(c) || c == '+' || c == '/'; } private IValue parseAbbrev(SharingStream reader) throws IOException { IValue result; int abbrev; int c = reader.read(); abbrev = 0; while (isBase64(c)) { abbrev *= 64; if (c >= 'A' && c <= 'Z') { abbrev += c - 'A'; } else if (c >= 'a' && c <= 'z') { abbrev += c - 'a' + 26; } else if (c >= '0' && c <= '9') { abbrev += c - '0' + 52; } else if (c == '+') { abbrev += 62; } else if (c == '/') { abbrev += 63; } else { throw new RuntimeException("not a base-64 digit: " + c); } c = reader.read(); } result = reader.getTerm(abbrev); return result; } private IValue parseNumber(SharingStream reader, Type expected) throws IOException { StringBuilder str = new StringBuilder(); IValue result; do { str.append((char) reader.getLastChar()); } while (Character.isDigit(reader.read())); if (reader.getLastChar() != '.' && reader.getLastChar() != 'e' && reader.getLastChar() != 'E' && reader.getLastChar() != 'l' && reader.getLastChar() != 'L') { int val; try { val = Integer.parseInt(str.toString()); } catch (NumberFormatException e) { throw new FactParseError("malformed int:" + str, reader.getPosition()); } result = expected.make(vf,ts, val); } else if (reader.getLastChar() == 'l' || reader.getLastChar() == 'L') { reader.read(); throw new FactParseError("No support for longs", reader.getPosition()); } else { if (reader.getLastChar() == '.') { str.append('.'); reader.read(); if (!Character.isDigit(reader.getLastChar())) throw new FactParseError("digit expected", reader.getPosition()); do { str.append((char) reader.getLastChar()); } while (Character.isDigit(reader.read())); } if (reader.getLastChar() == 'e' || reader.getLastChar() == 'E') { str.append((char) reader.getLastChar()); reader.read(); if (reader.getLastChar() == '-' || reader.getLastChar() == '+') { str.append((char) reader.getLastChar()); reader.read(); } if (!Character.isDigit(reader.getLastChar())) throw new FactParseError("digit expected!", reader.getPosition()); do { str.append((char) reader.getLastChar()); } while (Character.isDigit(reader.read())); } double val; try { val = Double.valueOf(str.toString()).doubleValue(); result = expected.make(vf,ts, val); } catch (NumberFormatException e) { throw new FactParseError("malformed real", reader.getPosition(), e); } } reader.skipWS(); return result; } private String parseId(SharingStream reader) throws IOException { int c = reader.getLastChar(); StringBuilder buf = new StringBuilder(32); do { buf.append((char) c); c = reader.read(); } while (Character.isLetterOrDigit(c) || c == '_' || c == '-' || c == '+' || c == '*' || c == '$' || c == '.'); // slight deviation here, allowing . inside of identifiers return buf.toString(); } private String parseStringLiteral(SharingStream reader) throws IOException { boolean escaped; StringBuilder str = new StringBuilder(); do { escaped = false; if (reader.read() == '\\') { reader.read(); escaped = true; } int lastChar = reader.getLastChar(); if(lastChar == -1) throw new IOException("Premature EOF."); if (escaped) { switch (lastChar) { case 'n': str.append('\n'); break; case 't': str.append('\t'); break; case 'b': str.append('\b'); break; case 'r': str.append('\r'); break; case 'f': str.append('\f'); break; case '\\': str.append('\\'); break; case '\'': str.append('\''); break; case '\"': str.append('\"'); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': str.append(reader.readOct()); break; default: str.append('\\').append((char) lastChar); } } else if (lastChar != '\"'){ str.append((char) lastChar); } } while (escaped || reader.getLastChar() != '"'); return str.toString(); } private IValue parseATerms(SharingStream reader, Type expected) throws IOException { Type base = expected; Type elementType = getElementType(expected); IValue[] terms = parseATermsArray(reader, elementType); if (base.isListType() || base.isValueType()) { IListWriter w = expected.writer(vf); for (int i = terms.length - 1; i >= 0; i--) { w.insert(terms[i]); } return w.done(); } else if (base.isSetType()) { ISetWriter w = expected.writer(vf); w.insert(terms); return w.done(); } else if (base.isMapType()) { IMapWriter w = expected.writer(vf); for (IValue elem : terms) { ITuple tuple = (ITuple) elem; w.put(tuple.get(0), tuple.get(1)); } return w.done(); } else if (base.isRelationType()) { ISetWriter w = expected.writer(vf); w.insert(terms); return w.done(); } throw new FactParseError("Unexpected type " + expected, reader.getPosition()); } private Type getElementType(Type expected) { Type base = expected; if (base.isListType()) { return base.getElementType(); } else if (base.isSetType()) { return base.getElementType(); } else if (base.isMapType()) { return tf.tupleType(base.getKeyType(), base.getValueType()); } else if (base.isRelationType()) { return base.getFieldTypes(); } else if (base.isValueType()) { return base; } else { throw new IllegalOperationException("getElementType", expected); } } private IValue[] parseATermsArray(SharingStream reader, Type elementType) throws IOException { List<IValue> list = new ArrayList<IValue>(2); IValue term = parse(reader, elementType); list.add(term); while (reader.getLastChar() == ',') { reader.readSkippingWS(); term = parse(reader, elementType); list.add(term); } IValue[] array = new IValue[list.size()]; ListIterator<IValue> iter = list.listIterator(); int index = 0; while (iter.hasNext()) { array[index++] = iter.next(); } return array; } private IValue[] parseFixedSizeATermsArray(SharingStream reader, Type elementTypes) throws IOException { List<IValue> list = new ArrayList<IValue>(elementTypes.getArity()); int i = 0; Type elementType = elementTypes.getFieldType(i++); IValue term = parse(reader, elementType); list.add(term); while (reader.getLastChar() == ',') { elementType = elementTypes.getFieldType(i++); reader.readSkippingWS(); term = parse(reader, elementType); list.add(term); } IValue[] array = new IValue[list.size()]; ListIterator<IValue> iter = list.listIterator(); int index = 0; while (iter.hasNext()) { array[index++] = iter.next(); } return array; } class SharingStream { private static final int INITIAL_TABLE_SIZE = 2048; private static final int TABLE_INCREMENT = 4096; private static final int INITIAL_BUFFER_SIZE = 1024; private InputStream reader; int last_char; private int pos; private int nr_terms; private IValue[] table; private byte[] buffer; private int limit; private int bufferPos; public SharingStream(InputStream reader) { this(reader, INITIAL_BUFFER_SIZE); } public SharingStream(InputStream stream, int bufferSize) { this.reader = stream; last_char = -1; pos = 0; if (bufferSize < INITIAL_BUFFER_SIZE) buffer = new byte[bufferSize]; else buffer = new byte[INITIAL_BUFFER_SIZE]; limit = -1; bufferPos = -1; } public void initializeSharing() { table = new IValue[INITIAL_TABLE_SIZE]; nr_terms = 0; } public void storeNextTerm(IValue t, int size) { if (table == null) { return; } if (nr_terms == table.length) { IValue[] new_table = new IValue[table.length + TABLE_INCREMENT]; System.arraycopy(table, 0, new_table, 0, table.length); table = new_table; } table[nr_terms++] = t; } public IValue getTerm(int index) { if (index < 0 || index >= nr_terms) { throw new RuntimeException("illegal index"); } return table[index]; } public int read() throws IOException { if (bufferPos == limit) { limit = reader.read(buffer); bufferPos = 0; } if (limit == -1) { last_char = -1; } else { last_char = buffer[bufferPos++]; pos++; } return last_char; } public int readSkippingWS() throws IOException { do { last_char = read(); } while (Character.isWhitespace(last_char)); return last_char; } public int skipWS() throws IOException { while (Character.isWhitespace(last_char)) { last_char = read(); } return last_char; } public int readOct() throws IOException { int val = Character.digit(last_char, 8); val += Character.digit(read(), 8); if (val < 0) { throw new FactParseError("octal must have 3 octdigits.", getPosition()); } val += Character.digit(read(), 8); if (val < 0) { throw new FactParseError("octal must have 3 octdigits", getPosition()); } return val; } public int getLastChar() { return last_char; } public int getPosition() { return pos; } } }
false
true
private IValue parseAppl(SharingStream reader, Type expected) throws IOException { int c; IValue result; c = reader.getLastChar(); if (Character.isLetter(c)) { String funname = parseId(reader); Type node; if (expected.isAbstractDataType()) { Set<Type> nodes = ts.lookupConstructor(expected, funname); // TODO deal with overloading Iterator<Type> iterator = nodes.iterator(); if (!iterator.hasNext()) { throw new UndeclaredAbstractDataTypeException(expected); } node = iterator.next(); } else { node = expected; } c = reader.skipWS(); if (reader.getLastChar() == '(') { c = reader.readSkippingWS(); if (c == -1) { throw new FactParseError("premature EOF encountered.", reader.getPosition()); } if (reader.getLastChar() == ')') { result = vf.constructor(node, new IValue[0]); } else { IValue[] list; if (expected.isAbstractDataType()) { list = parseFixedSizeATermsArray(reader, node.getFieldTypes()); } else { list = parseATermsArray(reader, TypeFactory.getInstance().valueType()); } if (reader.getLastChar() != ')') { throw new FactParseError("expected ')' but got '" + (char) reader.getLastChar() + "'", reader.getPosition()); } if (expected.isAbstractDataType()) { result = node.make(vf, list); } else { result = node.make(vf, funname, list); } } c = reader.readSkippingWS(); } else { if (node.isAbstractDataType() || node.isConstructorType()) { result = node.make(vf); } else { result = tf.nodeType().make(vf, funname); } } } else { throw new FactParseError("illegal character: " + (char) reader.getLastChar(), reader.getPosition()); } return result; }
private IValue parseAppl(SharingStream reader, Type expected) throws IOException { int c; IValue result; c = reader.getLastChar(); if (Character.isLetter(c)) { String funname = parseId(reader); Type node; if (expected.isAbstractDataType()) { Set<Type> nodes = ts.lookupConstructor(expected, funname); // TODO deal with overloading Iterator<Type> iterator = nodes.iterator(); if (!iterator.hasNext()) { throw new UndeclaredAbstractDataTypeException(expected); } node = iterator.next(); } else { node = expected; } c = reader.skipWS(); if (reader.getLastChar() == '(') { c = reader.readSkippingWS(); if (c == -1) { throw new FactParseError("premature EOF encountered.", reader.getPosition()); } if (reader.getLastChar() == ')') { result = node.make(vf, ts, funname, new IValue[0]); } else { IValue[] list; if (expected.isAbstractDataType()) { list = parseFixedSizeATermsArray(reader, node.getFieldTypes()); } else { list = parseATermsArray(reader, TypeFactory.getInstance().valueType()); } if (reader.getLastChar() != ')') { throw new FactParseError("expected ')' but got '" + (char) reader.getLastChar() + "'", reader.getPosition()); } if (expected.isAbstractDataType()) { result = node.make(vf, ts, funname, list); } else { result = node.make(vf, ts, funname, list); } } c = reader.readSkippingWS(); } else { if (node.isAbstractDataType() || node.isConstructorType()) { result = node.make(vf, ts); } else { result = tf.nodeType().make(vf, ts, funname); } } } else { throw new FactParseError("illegal character: " + (char) reader.getLastChar(), reader.getPosition()); } return result; }
diff --git a/ue3/src/main/java/formel0api/beans/LoginSession.java b/ue3/src/main/java/formel0api/beans/LoginSession.java index 83808df..cb60873 100644 --- a/ue3/src/main/java/formel0api/beans/LoginSession.java +++ b/ue3/src/main/java/formel0api/beans/LoginSession.java @@ -1,118 +1,119 @@ package formel0api.beans; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import formel0api.Game; /** * An instance of this class manage the login of a player. * The Player must already be known by the Registrar in order to * successfully login. * */ @ManagedBean(name="loginControl") @SessionScoped public class LoginSession { @ManagedProperty(value="#{registrar}") private Registrar registrar; private Player player; private Player computer; private Game game; boolean loginfailed = false; private String playerName; private String playerPassword; /** Creates a new instance of LoginCtrl */ public LoginSession() { } //Getters and Setters for Bean public void setRegistrar(Registrar registrar) { this.registrar = registrar; } public String getPlayerName() { return playerName; } public void setPlayerName(String name) { this.playerName = name; } public String getPlayerPassword() { return playerPassword; } public void setPlayerPassword(String pwd) { this.playerPassword = pwd; } public Player getPlayer() { return player; } public boolean isLoginfailed() { return loginfailed; } public void setLoginfailed(boolean loginfailed) { this.loginfailed = loginfailed; } public Game getGame(){ return game; } //Login - check password public String login() { if (registrar.getPlayer(playerName)!=null && registrar.getPlayer(playerName).getPassword().equals(playerPassword)) { player = registrar.getPlayer(playerName); computer = new Player(); + computer.setName("Super C"); computer.setFirstName("Super"); computer.setLastName("C"); loginfailed = false; startNewGame(); return "/table.xhtml"; } else { loginfailed = true; return "/index.xhtml"; } } // logout current user public String logout() { FacesContext.getCurrentInstance().getExternalContext().invalidateSession(); return "/index.xhtml"; } public void play() { if(!game.isGameOver()) { game.setRound(game.getRound()+1); game.rollthedice(game.getPlayer()); if(!game.isGameOver()) { game.rollthedice(game.getComputer()); } } } public String startNewGame() { player.reset(); computer.reset(); game = new Game(player, computer); return "/table.xhtml"; } }
true
true
public String login() { if (registrar.getPlayer(playerName)!=null && registrar.getPlayer(playerName).getPassword().equals(playerPassword)) { player = registrar.getPlayer(playerName); computer = new Player(); computer.setFirstName("Super"); computer.setLastName("C"); loginfailed = false; startNewGame(); return "/table.xhtml"; } else { loginfailed = true; return "/index.xhtml"; } }
public String login() { if (registrar.getPlayer(playerName)!=null && registrar.getPlayer(playerName).getPassword().equals(playerPassword)) { player = registrar.getPlayer(playerName); computer = new Player(); computer.setName("Super C"); computer.setFirstName("Super"); computer.setLastName("C"); loginfailed = false; startNewGame(); return "/table.xhtml"; } else { loginfailed = true; return "/index.xhtml"; } }
diff --git a/src/test/RegExpTests.java b/src/test/RegExpTests.java index c648d5a9f4..385db1fa26 100644 --- a/src/test/RegExpTests.java +++ b/src/test/RegExpTests.java @@ -1,158 +1,158 @@ package test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.meta_environment.rascal.interpreter.staticErrors.RedeclaredVariableError; import org.meta_environment.rascal.interpreter.staticErrors.SyntaxError; public class RegExpTests extends TestFramework{ @Test public void match() { assertTrue(runTest("/abc/ := \"abc\";")); assertFalse(runTest("/def/ := \"abc\";")); assertTrue(runTest("/def/ !:= \"abc\";")); assertTrue(runTest("/[a-z]+/ := \"abc\";")); assertTrue(runTest("/.*is.*/ := \"Rascal is marvelous\";")); assertTrue(runTest("/@.*@/ := \"@ abc @\";")); assertTrue(runTest("(/<x:[a-z]+>/ := \"abc\") && (x == \"abc\");")); - assertTrue(runTest("(/if<tst:.*>then<th:.*>fi/ := \"if a > b then c fi\") " + - "&& (tst == \" a > b \") && (th == \" c \");")); + assertTrue(runTest("(/if<tst:.*>then<th:.*>fi/ := \"if a \\> b then c fi\") " + + "&& (tst == \" a \\> b \") && (th == \" c \");")); assertTrue(runTest("(/<l:.*>[Rr][Aa][Ss][Cc][Aa][Ll]<r:.*>/ := \"RASCAL is marvelous\")" + "&& (l == \"\") && (r == \" is marvelous\");")); assertTrue(runTest("{str x = \"abc\"; /<x>/ := \"abc\";}")); assertTrue(runTest("{str x = \"abc\"; int n = 3; /<x><n>/ := \"abc3\";}")); assertTrue(runTest("(/<x:[a-z]+>-<x>/ := \"abc-abc\") && (x == \"abc\");")); assertTrue(runTest("(/<x:[a-z]+>-<x>-<x>/ := \"abc-abc-abc\") && (x == \"abc\");")); assertFalse(runTest("(/<x:[a-z]+>-<x>/ := \"abc-def\");")); } @Test(expected=RedeclaredVariableError.class) public void RedeclaredError(){ assertTrue(runTest("(/<x:[a-z]+>-<x:[a-z]+>/ := \"abc-abc\") && (x == \"abc\");")); } @Test public void matchWithLocalVariable(){ assertTrue(runTest("{ str x; (/<x:[a-z]+>/ := \"abc\") && (x == \"abc\");}")); assertTrue(runTest("{ str x = \"123\"; (/<x:[a-z]+>/ := \"abc\") && (x == \"abc\");}")); assertTrue(runTest("{ str x = \"123\"; (/<x:[a-z]+>/ := \"abc\"); (x == \"123\");}")); } @Test public void matchWithLocalVariableOfNonStringType(){ assertTrue(runTest("{ int x; (/<x:[a-z]+>/ := \"abc\") && (x == \"abc\");}")); assertTrue(runTest("{ int x = 123; (/<x:[a-z]+>/ := \"abc\") && (x == \"abc\");}")); assertTrue(runTest("{ int x = 123; (/<x:[a-z]+>/ := \"abc\"); (x == 123);}")); } @Test public void nomatchWithLocalVariable(){ assertTrue(runTest("{ str x = \"123\"; (/<x:[a-z]+>/ !:= \"abc\" && x == \"abc\");}")); assertTrue(runTest("{ str x = \"123\"; (/<x:[a-z]+>/ !:= \"abc\"); (x == \"123\");}")); } @Test public void InterpolateInPatternVarDecl(){ assertTrue(runTest("{ int n = 3; (/<x:<n>>/ := \"3\" && x == \"3\");}")); assertTrue(runTest("{ int n = 3; (/<x:<n>><x>/ := \"33\" && x == \"3\");}")); assertTrue(runTest("{ int n = 3; (/<x:a<n>>/ := \"a3\" && x == \"a3\");}")); assertTrue(runTest("{ int n = 3; (/<x:<n>b>/ := \"3b\" && x == \"3b\");}")); assertTrue(runTest("{ int n = 3; (/<x:a<n>b>/ := \"a3b\" && x == \"a3b\");}")); assertTrue(runTest("{ int n = 3; (/<x:a<n>b>/ := \"a3b\" && x == \"a3b\");}")); assertTrue(runTest("{ int n = 3; (/<x:a<n>b<n>c>/ := \"a3b3c\" && x == \"a3b3c\");}")); assertTrue(runTest("{ int n = 3; (/<x:a<n>b<n>c><x>/ := \"a3b3ca3b3c\" && x == \"a3b3c\");}")); assertTrue(runTest("{ int n = 3; (/<x:a{<n>}>/ := \"aaa\" && x == \"aaa\");}")); assertTrue(runTest("{ str a = \"a\"; int n = 3; (/<x:<a>{<n>}>/ := \"aaa\" && x == \"aaa\");}")); assertTrue(runTest("{ str a = \"abc\"; int n = 3; (/<x:(<a>){<n>}>/ := \"abcabcabc\" && x == \"abcabcabc\");}")); assertTrue(runTest("{ int n = 3; (/<x:\\\\>/ := \"\\\\\" && x == \"\\\\\");}")); assertTrue(runTest("{ int n = 3; (/<x:\\>>/ := \"\\>\" && x == \"\\>\");}")); assertTrue(runTest("{ int n = 3; (/<x:\\<>/ := \"\\<\" && x == \"\\<\");}")); assertTrue(runTest("{ int n = 3; (/<x:\\<<n>>/ := \"\\<3\" && x == \"\\<3\");}")); assertTrue(runTest("{ int n = 3; (/<x:\\<<n>\\>>/ := \"\\<3\\>\" && x == \"\\<3\\>\");}")); } @Test public void multipleMatches(){ assertTrue(runTest("[<x, y> | /<x:[a-z]+?><y:[a-z]+?>/ := \"abcd\"] == [<\"a\", \"b\">, <\"c\", \"d\">];")); assertTrue(runTest("[y | /<x:abc><y:...>/ := \"abc111abc222abc333\"] == [\"111\", \"222\", \"333\"];")); assertTrue(runTest("{int n = 3; [y | /<x:abc><y:.{<n>}>/ := \"abc111abc222abc333\"] == [\"111\", \"222\", \"333\"];}")); assertTrue(runTest("[s | /<s:.>/ := \"abcdef\"] == [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"];")); } @Test public void matchWithExternalModuleVariable(){ prepareModule("XX", "module XX str x = \"abc\";"); runTestInSameEvaluator("import XX;"); assertTrue(runTestInSameEvaluator("(/<x:[a-z]+>/ := \"abc\") && (x == \"abc\");")); } @Test public void nomatchWithExternalModuleVariable(){ prepareModule("XX", "module XX public str x = \"abc\";"); runTestInSameEvaluator("import XX;"); assertTrue(runTestInSameEvaluator("(/<x:[a-z]+>/ !:= \"pqr\") && (x == \"pqr\");")); assertTrue(runTestInSameEvaluator("{(/<x:[a-z]+>/ !:= \"pqr\") ; (x == \"abc\");}")); } @Test public void matchWithExternalModuleVariableOfWrongType(){ prepareModule("XX", "module XX int x = 123;"); assertTrue(runTestInSameEvaluator("(/<x:[a-z]+>/ := \"abc\") && (x == \"abc\");")); } @Test(expected=SyntaxError.class) public void RegExpSyntaxError1(){ runTest("/[a-/ := \"abc\";"); } @Test public void modifiers() { assertTrue(runTest("/abc/i := \"ABC\";")); assertTrue(runTest("/abc/i := \"ABC\";")); assertTrue(runTest("/ab.*c/s := \"ab\\nc\";")); assertTrue(runTest("/ab.*c/si := \"AB\\nc\";")); assertTrue(runTest("/^ab.*c$/smd := \"ab\\r\\nc\";")); } @Test public void wordCount1(){ String cnt = "int cnt(str S){" + " int count = 0;" + " while (/^\\W*<word:\\w+><rest:.*$>/ := S) { " + " count = count + 1;" + " S = rest;" + " }" + " return count;" + "}"; assertTrue(runTest("{" + cnt + "cnt(\"abc def ghi\") == 3;}")); } @Test public void wordCount2(){ String cnt = "int cnt(str S){" + " int count = 0;" + " while (/^\\W*<word:\\w+><rest:.*$>/ := S) { " + " count = count + 1;" + " S = rest;" + " }" + " return count;" + "}"; assertTrue(runTest("{" + cnt + "cnt(\"abc def ghi\") == 3;}")); } }
true
true
public void match() { assertTrue(runTest("/abc/ := \"abc\";")); assertFalse(runTest("/def/ := \"abc\";")); assertTrue(runTest("/def/ !:= \"abc\";")); assertTrue(runTest("/[a-z]+/ := \"abc\";")); assertTrue(runTest("/.*is.*/ := \"Rascal is marvelous\";")); assertTrue(runTest("/@.*@/ := \"@ abc @\";")); assertTrue(runTest("(/<x:[a-z]+>/ := \"abc\") && (x == \"abc\");")); assertTrue(runTest("(/if<tst:.*>then<th:.*>fi/ := \"if a > b then c fi\") " + "&& (tst == \" a > b \") && (th == \" c \");")); assertTrue(runTest("(/<l:.*>[Rr][Aa][Ss][Cc][Aa][Ll]<r:.*>/ := \"RASCAL is marvelous\")" + "&& (l == \"\") && (r == \" is marvelous\");")); assertTrue(runTest("{str x = \"abc\"; /<x>/ := \"abc\";}")); assertTrue(runTest("{str x = \"abc\"; int n = 3; /<x><n>/ := \"abc3\";}")); assertTrue(runTest("(/<x:[a-z]+>-<x>/ := \"abc-abc\") && (x == \"abc\");")); assertTrue(runTest("(/<x:[a-z]+>-<x>-<x>/ := \"abc-abc-abc\") && (x == \"abc\");")); assertFalse(runTest("(/<x:[a-z]+>-<x>/ := \"abc-def\");")); }
public void match() { assertTrue(runTest("/abc/ := \"abc\";")); assertFalse(runTest("/def/ := \"abc\";")); assertTrue(runTest("/def/ !:= \"abc\";")); assertTrue(runTest("/[a-z]+/ := \"abc\";")); assertTrue(runTest("/.*is.*/ := \"Rascal is marvelous\";")); assertTrue(runTest("/@.*@/ := \"@ abc @\";")); assertTrue(runTest("(/<x:[a-z]+>/ := \"abc\") && (x == \"abc\");")); assertTrue(runTest("(/if<tst:.*>then<th:.*>fi/ := \"if a \\> b then c fi\") " + "&& (tst == \" a \\> b \") && (th == \" c \");")); assertTrue(runTest("(/<l:.*>[Rr][Aa][Ss][Cc][Aa][Ll]<r:.*>/ := \"RASCAL is marvelous\")" + "&& (l == \"\") && (r == \" is marvelous\");")); assertTrue(runTest("{str x = \"abc\"; /<x>/ := \"abc\";}")); assertTrue(runTest("{str x = \"abc\"; int n = 3; /<x><n>/ := \"abc3\";}")); assertTrue(runTest("(/<x:[a-z]+>-<x>/ := \"abc-abc\") && (x == \"abc\");")); assertTrue(runTest("(/<x:[a-z]+>-<x>-<x>/ := \"abc-abc-abc\") && (x == \"abc\");")); assertFalse(runTest("(/<x:[a-z]+>-<x>/ := \"abc-def\");")); }
diff --git a/src/com/android/dreams/web/Screensaver.java b/src/com/android/dreams/web/Screensaver.java index 39a4146..65965ec 100644 --- a/src/com/android/dreams/web/Screensaver.java +++ b/src/com/android/dreams/web/Screensaver.java @@ -1,89 +1,89 @@ /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.dreams.web; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.TimeInterpolator; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Configuration; import android.graphics.drawable.Drawable; import android.graphics.PorterDuff; import android.net.Uri; import android.os.BatteryManager; import android.os.Handler; import android.provider.Settings; import android.service.dreams.Dream; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.animation.AccelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.widget.TextView; public class Screensaver extends Dream { @Override public void onStart() { super.onStart(); } private class LinkLauncher extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); return true; } } @Override public void onAttachedToWindow() { super.onAttachedToWindow(); setContentView(R.layout.main); - lightsOut(); // lights out, fullscreen + setFullscreen(true); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); final String url = prefs.getString("url", "file:///android_asset/default.html"); final boolean interactive = prefs.getBoolean("interactive", false); Log.v("WebViewDream", String.format("loading %s in %s mode", url, interactive ? "interactive" : "noninteractive")); setInteractive(interactive); WebView webview = (WebView) findViewById(R.id.webview); webview.setWebViewClient(new LinkLauncher()); WebSettings webSettings = webview.getSettings(); webSettings.setJavaScriptEnabled(true); webview.loadUrl(url); } }
true
true
public void onAttachedToWindow() { super.onAttachedToWindow(); setContentView(R.layout.main); lightsOut(); // lights out, fullscreen final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); final String url = prefs.getString("url", "file:///android_asset/default.html"); final boolean interactive = prefs.getBoolean("interactive", false); Log.v("WebViewDream", String.format("loading %s in %s mode", url, interactive ? "interactive" : "noninteractive")); setInteractive(interactive); WebView webview = (WebView) findViewById(R.id.webview); webview.setWebViewClient(new LinkLauncher()); WebSettings webSettings = webview.getSettings(); webSettings.setJavaScriptEnabled(true); webview.loadUrl(url); }
public void onAttachedToWindow() { super.onAttachedToWindow(); setContentView(R.layout.main); setFullscreen(true); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); final String url = prefs.getString("url", "file:///android_asset/default.html"); final boolean interactive = prefs.getBoolean("interactive", false); Log.v("WebViewDream", String.format("loading %s in %s mode", url, interactive ? "interactive" : "noninteractive")); setInteractive(interactive); WebView webview = (WebView) findViewById(R.id.webview); webview.setWebViewClient(new LinkLauncher()); WebSettings webSettings = webview.getSettings(); webSettings.setJavaScriptEnabled(true); webview.loadUrl(url); }
diff --git a/src/org/plovr/Manifest.java b/src/org/plovr/Manifest.java index 8c711736c..6fdbcf1d8 100644 --- a/src/org/plovr/Manifest.java +++ b/src/org/plovr/Manifest.java @@ -1,442 +1,442 @@ package org.plovr; import java.io.File; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.logging.Logger; import javax.annotation.Nullable; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.gson.Gson; import com.google.javascript.jscomp.JSModule; import com.google.javascript.jscomp.JSSourceFile; /** * {@link Manifest} represents an ordered list of JavaScript inputs to the * Closure Compiler, along with a set of externs. This list is derived from the * transitive closure of the dependencies from a set of input files. * * @author [email protected] (Michael Bolin) */ public final class Manifest { private static final Logger logger = Logger.getLogger(Manifest.class.getName()); /** * Converts a plovr JsInput to a Closure Compiler JSSourceFile. */ static Function<JsInput, JSSourceFile> inputToSourceFile = new Function<JsInput, JSSourceFile>() { @Override public JSSourceFile apply(JsInput jsInput) { return JSSourceFile.fromGenerator(jsInput.getName(), jsInput); } }; private final boolean excludeClosureLibrary; private final File closureLibraryDirectory; private final Set<File> dependencies; private final List<JsInput> requiredInputs; private final Set<File> externs; private final Set<JsInput> builtInExterns; private final boolean customExternsOnly; /** * When RAW mode is used, each input will need to be accessed by name. To make * the lookup efficient, populate this map when getInputsInCompilationOrder() * is called to prepare for the requests that are about to occur. */ private Map<String, JsInput> lastOrdering; private final SoyFileOptions soyFileOptions; // If excludeClosureLibrary ends up being a permanent option, then // eliminate this constructor. Manifest( @Nullable File closureLibraryDirectory, List<File> dependencies, List<JsInput> requiredInputs, @Nullable List<File> externs, @Nullable List<JsInput> builtInExterns, SoyFileOptions soyFileOptions, boolean customExternsOnly) { this( false /* boolean excludeClosureLibrary */, closureLibraryDirectory, dependencies, requiredInputs, externs, builtInExterns, soyFileOptions, customExternsOnly); } /** * * @param closureLibraryDirectory Directory that is the root of the Closure * Library (must contain base.js) * @param dependencies files (or directories) that contain JS inputs that * may be included in the compilation * @param requiredInputs files (or directories) that contain JS inputs that * must be included in the compilation * @param externs files (or directories) that contain JS externs */ Manifest( boolean excludeClosureLibrary, @Nullable File closureLibraryDirectory, List<File> dependencies, List<JsInput> requiredInputs, @Nullable List<File> externs, @Nullable List<JsInput> builtInExterns, SoyFileOptions soyFileOptions, boolean customExternsOnly) { Preconditions.checkNotNull(dependencies); Preconditions.checkNotNull(requiredInputs); Preconditions.checkArgument(requiredInputs.size() > 0, "No inputs were specified! " + "Make sure there is an option named 'inputs' in the config file"); Preconditions.checkNotNull(soyFileOptions); // TODO(bolinfest): Monitor directories for changes and have the JsInput // mark itself dirty when there is a change. this.excludeClosureLibrary = excludeClosureLibrary; this.closureLibraryDirectory = closureLibraryDirectory; this.dependencies = ImmutableSet.copyOf(dependencies); this.requiredInputs = ImmutableList.copyOf(requiredInputs); this.externs = externs == null ? null : ImmutableSet.copyOf(externs); this.builtInExterns = builtInExterns == null ? null : ImmutableSet.copyOf(builtInExterns); this.soyFileOptions = soyFileOptions; this.customExternsOnly = customExternsOnly; } /** * @return the set of files (or directories) that contain JS inputs that * may be included in the compilation */ public Set<File> getDependencies() { return ImmutableSet.copyOf(dependencies); } /** * @return a list of files (or directories) that contain JS inputs that * must be included in the compilation */ public List<JsInput> getRequiredInputs() { return ImmutableList.copyOf(requiredInputs); } /** * @param moduleConfig * @return a new {@link Compilation} that reflects the configuration for * this {@link Manifest}. * @throws CompilationException */ public Compilation getCompilerArguments( @Nullable ModuleConfig moduleConfig) throws CompilationException { // Build up the list of externs to use in the compilation. ImmutableList.Builder<JSSourceFile> builder = ImmutableList.builder(); if (!customExternsOnly) { builder.addAll(getDefaultExterns()); } if (this.externs != null) { builder.addAll(Lists.transform(getExternInputs(), inputToSourceFile)); } if (this.builtInExterns != null) { builder.addAll(Iterables.transform(builtInExterns, inputToSourceFile)); } List<JSSourceFile> externs = builder.build(); if (moduleConfig == null) { List<JsInput> jsInputs = getInputsInCompilationOrder(); List<JSSourceFile> inputs = Lists.transform(jsInputs, inputToSourceFile); logger.config("Inputs: " + jsInputs.toString()); return Compilation.create(externs, inputs); } else { List<JSModule> modules = moduleConfig.getModules(this); return Compilation.createForModules(externs, modules); } } private List<JSSourceFile> getDefaultExterns() { logger.fine("Using default externs"); return ResourceReader.getDefaultExterns(); } public List<JsInput> getInputsInCompilationOrder() throws CompilationException { Set<JsInput> allDependencies = getAllDependencies(); Map<String, JsInput> provideToSource = getProvideToSource(allDependencies); LinkedHashSet<JsInput> compilerInputs = new LinkedHashSet<JsInput>(); if (!this.excludeClosureLibrary) { compilerInputs.add(getBaseJs()); compilerInputs.add(getDepsJs()); } for (JsInput requiredInput : requiredInputs) { buildDependencies(provideToSource, compilerInputs, requiredInput); } // Update lastOrdering before returning. Map<String, JsInput> lastOrdering = Maps.newHashMap(); for (JsInput input : compilerInputs) { lastOrdering.put(input.getName(), input); } this.lastOrdering = lastOrdering; return ImmutableList.copyOf(compilerInputs); } Map<String, JsInput> getProvideToSource(Set<JsInput> allDependencies) { // Build up the dependency graph. Map<String, JsInput> provideToSource = Maps.newHashMap(); for (JsInput input : allDependencies) { List<String> provides = input.getProvides(); for (String provide : provides) { JsInput existingProvider = provideToSource.get(provide); if (existingProvider != null) { throw new IllegalStateException(provide + " is provided by both " + existingProvider + " and " + input); } provideToSource.put(provide, input); } } return provideToSource; } boolean isUseClosureLibrary() { return !this.excludeClosureLibrary; } JsInput getBaseJs() { if (isBuiltInClosureLibrary()) { return ResourceReader.getBaseJs(); } else { // TODO: Use a Supplier so that this is only done once. return new JsSourceFile("/base.js", new File(closureLibraryDirectory, "base.js")); } } boolean isBuiltInClosureLibrary() { return closureLibraryDirectory == null; } JsInput getDepsJs() { Preconditions.checkState(!this.excludeClosureLibrary); String depsJs = buildDepsJs(); return new DepsJsInput(getBaseJs(), depsJs); } JsInput getJsInputByName(String name) { if (lastOrdering == null) { // It is possible that a file could be requested from the manifest before // a compilation is done, such as when a user navigates directly to /view. // In that case, lastOrdering will be null, so invoke // getInputsInCompilationOrder() so that it gets initialized. try { // TODO(bolinfest): Create a utility method that just traverses the list // of inputs and dependencies as the ordering is not actually needed at // this point. Such a utility method would not throw a // CompilationException. getInputsInCompilationOrder(); } catch (CompilationException e) { throw new RuntimeException(e); } } return lastOrdering.get(name); } void buildDependencies(Map<String, JsInput> provideToSource, LinkedHashSet<JsInput> transitiveDependencies, JsInput input) throws CompilationException { buildDependenciesInternal(provideToSource, transitiveDependencies, new LinkedHashSet<JsInput>(), input); } void buildDependenciesInternal(Map<String, JsInput> provideToSource, LinkedHashSet<JsInput> transitiveDependencies, LinkedHashSet<JsInput> currentDependencyChain, JsInput input) throws CompilationException { // Avoid infinite by going depth-first and never revisiting a node. if (currentDependencyChain.contains(input)) { throw new CircularDependencyException(input, currentDependencyChain); } currentDependencyChain.add(input); for (String require : input.getRequires()) { JsInput provide = provideToSource.get(require); if (provide == null) { throw new MissingProvideException(input, require); } // It is possible that this dependency has already been included in the // set of transitive dependencies, in which case its dependencies should // not be built again. if (transitiveDependencies.contains(provide)) { continue; } buildDependenciesInternal(provideToSource, transitiveDependencies, currentDependencyChain, provide); } transitiveDependencies.add(input); currentDependencyChain.remove(input); } Set<JsInput> getAllDependencies() { Set<JsInput> allDependencies = Sets.newHashSet(); final boolean externsOnly = false; if (isBuiltInClosureLibrary()) { allDependencies.addAll(ResourceReader.getClosureLibrarySources()); } else { allDependencies.addAll(getFiles(closureLibraryDirectory, externsOnly)); } // Add the requiredInputs first so that if a file is both an "input" and a // "path" under different names (such as "hello.js" and "/./hello.js"), the // name used to specify the input is preferred. allDependencies.addAll(requiredInputs); allDependencies.addAll(getFiles(dependencies, externsOnly)); return allDependencies; } private List<JsInput> getExternInputs() { final boolean externsOnly = true; List<JsInput> externInputs = Lists.newArrayList(getFiles(externs, externsOnly)); return ImmutableList.copyOf(externInputs); } private Set<JsInput> getFiles(File fileToExpand, boolean externsOnly) { return getFiles(Sets.newHashSet(fileToExpand), externsOnly); } private Set<JsInput> getFiles(Set<File> filesToExpand, boolean externsOnly) { Set<JsInput> inputs = Sets.newHashSet(); for (File file : filesToExpand) { getInputs(file, inputs, externsOnly, file); } return ImmutableSet.copyOf(inputs); } /** * * @param rootOfSearch is the directory where this search started -- this is * used to determine the relative path of the resulting input */ private void getInputs(File file, Set<JsInput> output, boolean externsOnly, final File rootOfSearch) { // Some editors may write backup files whose names start with a // dot. Furthermore, Emacs will create symlinks that start with a // dot that don't point at actual files, causing file.exists() to // not work. Such files should be ignored. (If this turns out to // be an issue, this could be changed so it is configurable.) One // common exception is when the name is simply ".", referring to // the current directory. if (file.getName().startsWith(".") && !".".equals(file.getName())) { logger.info("Ignoring: " + file); return; } Preconditions.checkArgument(file.exists(), "File not found at: " + file.getAbsolutePath()); Function<File, String> getRelativePath = new Function<File, String>() { @Override public String apply(File file) { // If the root of the search is a file rather than a directory, then it // should be the file parameter to getInputs(). In that case, just use // the name of the file as the name of the JsInput. if (!rootOfSearch.isDirectory()) { Preconditions.checkArgument(rootOfSearch.equals(file)); return file.getName(); } - String rootPath = rootOfSearch.getAbsolutePath(); - String fullPath = file.getAbsolutePath(); - return fullPath.substring(rootPath.length()); + String rootPath = rootOfSearch.toURI().toString(); + String fullPath = file.toURI().toString(); + return "/" + fullPath.substring(rootPath.length()); } }; if (file.isFile()) { String fileName = file.getName(); if (fileName.endsWith(".js") || (!externsOnly && fileName.endsWith(".soy")) || (!externsOnly && fileName.endsWith(".coffee"))) { // Using "." as the value for "paths" in the config file results in ugly // names for JsInputs because of the way the relative path is resolved, // so strip the leading "/./" from the JsInput name in this case. String name = getRelativePath.apply(file); final String uglyPrefix = "/./"; if (name.startsWith(uglyPrefix)) { name = name.substring(uglyPrefix.length()); } JsInput input = LocalFileJsInput.createForFileWithName(file, name, soyFileOptions); logger.config("Dependency: " + input); output.add(input); } } else if (file.isDirectory()) { logger.config("Directory to explore: " + file); for (File entry : file.listFiles()) { getInputs(entry, output, externsOnly, rootOfSearch); } } } /** * For compilation, the exact path to the input in the generated deps.js file * does not matter. */ private String buildDepsJs() { return buildDepsJs(new Function<JsInput, String>() { @Override public String apply(JsInput input) { return input.getName(); } }); } String buildDepsJs(Function<JsInput, String> converter) { StringBuilder builder = new StringBuilder(); SortedSet<JsInput> inputs = ImmutableSortedSet.copyOf( JsInputComparator.SINGLETON, getAllDependencies()); final Gson gson = new Gson(); Function<String, String> toJsString = new Function<String, String>() { @Override public String apply(String str) { return gson.toJson(str); } }; Joiner comma = Joiner.on(", "); for (JsInput input : inputs) { builder.append("goog.addDependency(" + toJsString.apply(converter.apply(input)) + ", [" + comma.join(Lists.transform(input.getProvides(), toJsString)) + "], [" + comma.join(Lists.transform(input.getRequires(), toJsString)) + "]);\n"); } return builder.toString(); } }
true
true
private void getInputs(File file, Set<JsInput> output, boolean externsOnly, final File rootOfSearch) { // Some editors may write backup files whose names start with a // dot. Furthermore, Emacs will create symlinks that start with a // dot that don't point at actual files, causing file.exists() to // not work. Such files should be ignored. (If this turns out to // be an issue, this could be changed so it is configurable.) One // common exception is when the name is simply ".", referring to // the current directory. if (file.getName().startsWith(".") && !".".equals(file.getName())) { logger.info("Ignoring: " + file); return; } Preconditions.checkArgument(file.exists(), "File not found at: " + file.getAbsolutePath()); Function<File, String> getRelativePath = new Function<File, String>() { @Override public String apply(File file) { // If the root of the search is a file rather than a directory, then it // should be the file parameter to getInputs(). In that case, just use // the name of the file as the name of the JsInput. if (!rootOfSearch.isDirectory()) { Preconditions.checkArgument(rootOfSearch.equals(file)); return file.getName(); } String rootPath = rootOfSearch.getAbsolutePath(); String fullPath = file.getAbsolutePath(); return fullPath.substring(rootPath.length()); } }; if (file.isFile()) { String fileName = file.getName(); if (fileName.endsWith(".js") || (!externsOnly && fileName.endsWith(".soy")) || (!externsOnly && fileName.endsWith(".coffee"))) { // Using "." as the value for "paths" in the config file results in ugly // names for JsInputs because of the way the relative path is resolved, // so strip the leading "/./" from the JsInput name in this case. String name = getRelativePath.apply(file); final String uglyPrefix = "/./"; if (name.startsWith(uglyPrefix)) { name = name.substring(uglyPrefix.length()); } JsInput input = LocalFileJsInput.createForFileWithName(file, name, soyFileOptions); logger.config("Dependency: " + input); output.add(input); } } else if (file.isDirectory()) { logger.config("Directory to explore: " + file); for (File entry : file.listFiles()) { getInputs(entry, output, externsOnly, rootOfSearch); } } }
private void getInputs(File file, Set<JsInput> output, boolean externsOnly, final File rootOfSearch) { // Some editors may write backup files whose names start with a // dot. Furthermore, Emacs will create symlinks that start with a // dot that don't point at actual files, causing file.exists() to // not work. Such files should be ignored. (If this turns out to // be an issue, this could be changed so it is configurable.) One // common exception is when the name is simply ".", referring to // the current directory. if (file.getName().startsWith(".") && !".".equals(file.getName())) { logger.info("Ignoring: " + file); return; } Preconditions.checkArgument(file.exists(), "File not found at: " + file.getAbsolutePath()); Function<File, String> getRelativePath = new Function<File, String>() { @Override public String apply(File file) { // If the root of the search is a file rather than a directory, then it // should be the file parameter to getInputs(). In that case, just use // the name of the file as the name of the JsInput. if (!rootOfSearch.isDirectory()) { Preconditions.checkArgument(rootOfSearch.equals(file)); return file.getName(); } String rootPath = rootOfSearch.toURI().toString(); String fullPath = file.toURI().toString(); return "/" + fullPath.substring(rootPath.length()); } }; if (file.isFile()) { String fileName = file.getName(); if (fileName.endsWith(".js") || (!externsOnly && fileName.endsWith(".soy")) || (!externsOnly && fileName.endsWith(".coffee"))) { // Using "." as the value for "paths" in the config file results in ugly // names for JsInputs because of the way the relative path is resolved, // so strip the leading "/./" from the JsInput name in this case. String name = getRelativePath.apply(file); final String uglyPrefix = "/./"; if (name.startsWith(uglyPrefix)) { name = name.substring(uglyPrefix.length()); } JsInput input = LocalFileJsInput.createForFileWithName(file, name, soyFileOptions); logger.config("Dependency: " + input); output.add(input); } } else if (file.isDirectory()) { logger.config("Directory to explore: " + file); for (File entry : file.listFiles()) { getInputs(entry, output, externsOnly, rootOfSearch); } } }
diff --git a/E-Adventure/src/es/eucm/eadventure/editor/gui/structurepanel/structureelements/Effects/MainStructureListElement.java b/E-Adventure/src/es/eucm/eadventure/editor/gui/structurepanel/structureelements/Effects/MainStructureListElement.java index dca4c199..310fb1f0 100644 --- a/E-Adventure/src/es/eucm/eadventure/editor/gui/structurepanel/structureelements/Effects/MainStructureListElement.java +++ b/E-Adventure/src/es/eucm/eadventure/editor/gui/structurepanel/structureelements/Effects/MainStructureListElement.java @@ -1,54 +1,54 @@ /******************************************************************************* * <e-Adventure> (formerly <e-Game>) is a research project of the <e-UCM> * research group. * * Copyright 2005-2010 <e-UCM> research group. * * You can access a list of all the contributors to <e-Adventure> at: * http://e-adventure.e-ucm.es/contributors * * <e-UCM> is a research group of the Department of Software Engineering * and Artificial Intelligence at the Complutense University of Madrid * (School of Computer Science). * * C Profesor Jose Garcia Santesmases sn, * 28040 Madrid (Madrid), Spain. * * For more info please visit: <http://e-adventure.e-ucm.es> or * <http://www.e-ucm.es> * * **************************************************************************** * * This file is part of <e-Adventure>, version 1.2. * * <e-Adventure> is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * <e-Adventure> is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with <e-Adventure>. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package es.eucm.eadventure.editor.gui.structurepanel.structureelements.Effects; import es.eucm.eadventure.common.gui.TC; public class MainStructureListElement extends EffectsStructureListElement { private static final String LIST_URL = "effects_short/Effects_General.html"; public MainStructureListElement( ) { super( TC.get( "EffectsGroup.Main" ) ); //icon = EffectsStructurePanel.getEffectIcon(name, EffectsStructurePanel.ICON_SIZE_MEDIUM); //new ImageIcon( "img/icons/adaptationProfiles.png" ); - groupEffects = new String[] { TC.get( "Effect.Activate" ), TC.get( "Effect.Deactivate" ), TC.get( "Effect.SetValue" ), TC.get( "Effect.IncrementVar" ), TC.get( "Effect.DecrementVar" ), TC.get( "Effect.PlaySound" ), TC.get( "Effect.PlayAnimation" ), TC.get( "Effect.SpeakPlayer" ), TC.get( "Effect.SpeakCharacter" ), TC.get( "Effect.ShowText" ), TC.get( "Effect.TriggerConversation" ), TC.get( "Effect.TriggerScene" ), TC.get( "Effect.TriggerLastScene" ), TC.get( "Effect.TriggerCutscene" ), TC.get( "Effect.TriggerBook" ), TC.get( "Effect.ConsumeObject" ), TC.get( "Effect.GenerateObject" ), TC.get( "Effect.MovePlayer" ), TC.get( "Effect.MoveCharacter" ), TC.get( "Effect.MacroReference" ), TC.get( "Effect.CancelAction" ), TC.get( "Effect.RandomEffect" ), TC.get( "Effect.WaitTime" ) }; + groupEffects = new String[] { TC.get( "Effect.Activate" ), TC.get( "Effect.Deactivate" ), TC.get( "Effect.SetValue" ), TC.get( "Effect.IncrementVar" ), TC.get( "Effect.DecrementVar" ), TC.get( "Effect.PlaySound" ), TC.get( "Effect.PlayAnimation" ), TC.get( "Effect.SpeakPlayer" ), TC.get( "Effect.SpeakCharacter" ), TC.get( "Effect.ShowText" ), TC.get( "Effect.TriggerConversation" ), TC.get( "Effect.TriggerScene" ), TC.get( "Effect.TriggerLastScene" ), TC.get( "Effect.TriggerCutscene" ), TC.get( "Effect.TriggerBook" ), TC.get( "Effect.ConsumeObject" ), TC.get( "Effect.GenerateObject" ), TC.get( "Effect.HighlightItem" ), TC.get( "Effect.MovePlayer" ), TC.get( "Effect.MoveCharacter" ),TC.get( "Effect.MoveObject" ), TC.get( "Effect.MacroReference" ), TC.get( "Effect.CancelAction" ), TC.get( "Effect.RandomEffect" ), TC.get( "Effect.WaitTime" ) }; path = LIST_URL; } }
true
true
public MainStructureListElement( ) { super( TC.get( "EffectsGroup.Main" ) ); //icon = EffectsStructurePanel.getEffectIcon(name, EffectsStructurePanel.ICON_SIZE_MEDIUM); //new ImageIcon( "img/icons/adaptationProfiles.png" ); groupEffects = new String[] { TC.get( "Effect.Activate" ), TC.get( "Effect.Deactivate" ), TC.get( "Effect.SetValue" ), TC.get( "Effect.IncrementVar" ), TC.get( "Effect.DecrementVar" ), TC.get( "Effect.PlaySound" ), TC.get( "Effect.PlayAnimation" ), TC.get( "Effect.SpeakPlayer" ), TC.get( "Effect.SpeakCharacter" ), TC.get( "Effect.ShowText" ), TC.get( "Effect.TriggerConversation" ), TC.get( "Effect.TriggerScene" ), TC.get( "Effect.TriggerLastScene" ), TC.get( "Effect.TriggerCutscene" ), TC.get( "Effect.TriggerBook" ), TC.get( "Effect.ConsumeObject" ), TC.get( "Effect.GenerateObject" ), TC.get( "Effect.MovePlayer" ), TC.get( "Effect.MoveCharacter" ), TC.get( "Effect.MacroReference" ), TC.get( "Effect.CancelAction" ), TC.get( "Effect.RandomEffect" ), TC.get( "Effect.WaitTime" ) }; path = LIST_URL; }
public MainStructureListElement( ) { super( TC.get( "EffectsGroup.Main" ) ); //icon = EffectsStructurePanel.getEffectIcon(name, EffectsStructurePanel.ICON_SIZE_MEDIUM); //new ImageIcon( "img/icons/adaptationProfiles.png" ); groupEffects = new String[] { TC.get( "Effect.Activate" ), TC.get( "Effect.Deactivate" ), TC.get( "Effect.SetValue" ), TC.get( "Effect.IncrementVar" ), TC.get( "Effect.DecrementVar" ), TC.get( "Effect.PlaySound" ), TC.get( "Effect.PlayAnimation" ), TC.get( "Effect.SpeakPlayer" ), TC.get( "Effect.SpeakCharacter" ), TC.get( "Effect.ShowText" ), TC.get( "Effect.TriggerConversation" ), TC.get( "Effect.TriggerScene" ), TC.get( "Effect.TriggerLastScene" ), TC.get( "Effect.TriggerCutscene" ), TC.get( "Effect.TriggerBook" ), TC.get( "Effect.ConsumeObject" ), TC.get( "Effect.GenerateObject" ), TC.get( "Effect.HighlightItem" ), TC.get( "Effect.MovePlayer" ), TC.get( "Effect.MoveCharacter" ),TC.get( "Effect.MoveObject" ), TC.get( "Effect.MacroReference" ), TC.get( "Effect.CancelAction" ), TC.get( "Effect.RandomEffect" ), TC.get( "Effect.WaitTime" ) }; path = LIST_URL; }
diff --git a/cdm/src/test/java/thredds/catalog/parser/jdom/TestReadMetadata.java b/cdm/src/test/java/thredds/catalog/parser/jdom/TestReadMetadata.java index 9f2fed65f..06024a623 100644 --- a/cdm/src/test/java/thredds/catalog/parser/jdom/TestReadMetadata.java +++ b/cdm/src/test/java/thredds/catalog/parser/jdom/TestReadMetadata.java @@ -1,64 +1,65 @@ package thredds.catalog.parser.jdom; import junit.framework.*; import thredds.catalog.InvCatalogFactory; import thredds.catalog.InvCatalogImpl; import thredds.catalog.InvDatasetImpl; import java.net.URI; import java.net.URISyntaxException; /** * _more_ * * @author edavis * @since 4.0 */ public class TestReadMetadata extends TestCase { public TestReadMetadata( String name ) { super( name ); } /** * Test ... */ public void testReadDatasetWithDataSize() { double sizeKb = 439.78; StringBuilder catAsString = new StringBuilder() .append( "<catalog xmlns=\"http://www.unidata.ucar.edu/namespaces/thredds/InvCatalog/v1.0\"\n" ) .append( " xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n" ) .append( " name=\"Catalog for TestReadMetadata.testReadDatasetWithDataSize()\"\n" ) .append( " version=\"1.0.1\">\n" ) .append( " <service name=\"gridded\" serviceType=\"OPENDAP\" base=\"/thredds/dodsC/\" />\n" ) .append( " <dataset name=\"Atmosphere\" ID=\"cgcm3.1_t47_atmos\" serviceName=\"gridded\">\n" ) .append( " <metadata inherited=\"false\">\n" ) .append( " <dataSize units=\"Kbytes\">").append( sizeKb ).append( "</dataSize>\n" ) .append( " </metadata>\n" ) .append( " </dataset>\n" ) .append( "</catalog>" ); String catUri = "Cat.TestReadMetadata.testReadDatasetWithDataSize"; URI catURI = null; try { catURI = new URI( catUri ); } catch ( URISyntaxException e ) { fail( "URISyntaxException: " + e.getMessage() ); return; } InvCatalogFactory fac = InvCatalogFactory.getDefaultFactory( false ); InvCatalogImpl cat = fac.readXML( catAsString.toString(), catURI ); - double d = ((InvDatasetImpl) cat.getDatasets().get( 0 )).getDataSize(); + InvDatasetImpl ds = (InvDatasetImpl) cat.getDatasets().get( 0 ); + double d = ds.getDataSize(); assertTrue( "Size of data <" + d + "> not as expected <" + sizeKb + ">.", d > sizeKb - 0.001 && d < sizeKb + 0.001 ); } }
true
true
public void testReadDatasetWithDataSize() { double sizeKb = 439.78; StringBuilder catAsString = new StringBuilder() .append( "<catalog xmlns=\"http://www.unidata.ucar.edu/namespaces/thredds/InvCatalog/v1.0\"\n" ) .append( " xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n" ) .append( " name=\"Catalog for TestReadMetadata.testReadDatasetWithDataSize()\"\n" ) .append( " version=\"1.0.1\">\n" ) .append( " <service name=\"gridded\" serviceType=\"OPENDAP\" base=\"/thredds/dodsC/\" />\n" ) .append( " <dataset name=\"Atmosphere\" ID=\"cgcm3.1_t47_atmos\" serviceName=\"gridded\">\n" ) .append( " <metadata inherited=\"false\">\n" ) .append( " <dataSize units=\"Kbytes\">").append( sizeKb ).append( "</dataSize>\n" ) .append( " </metadata>\n" ) .append( " </dataset>\n" ) .append( "</catalog>" ); String catUri = "Cat.TestReadMetadata.testReadDatasetWithDataSize"; URI catURI = null; try { catURI = new URI( catUri ); } catch ( URISyntaxException e ) { fail( "URISyntaxException: " + e.getMessage() ); return; } InvCatalogFactory fac = InvCatalogFactory.getDefaultFactory( false ); InvCatalogImpl cat = fac.readXML( catAsString.toString(), catURI ); double d = ((InvDatasetImpl) cat.getDatasets().get( 0 )).getDataSize(); assertTrue( "Size of data <" + d + "> not as expected <" + sizeKb + ">.", d > sizeKb - 0.001 && d < sizeKb + 0.001 ); }
public void testReadDatasetWithDataSize() { double sizeKb = 439.78; StringBuilder catAsString = new StringBuilder() .append( "<catalog xmlns=\"http://www.unidata.ucar.edu/namespaces/thredds/InvCatalog/v1.0\"\n" ) .append( " xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n" ) .append( " name=\"Catalog for TestReadMetadata.testReadDatasetWithDataSize()\"\n" ) .append( " version=\"1.0.1\">\n" ) .append( " <service name=\"gridded\" serviceType=\"OPENDAP\" base=\"/thredds/dodsC/\" />\n" ) .append( " <dataset name=\"Atmosphere\" ID=\"cgcm3.1_t47_atmos\" serviceName=\"gridded\">\n" ) .append( " <metadata inherited=\"false\">\n" ) .append( " <dataSize units=\"Kbytes\">").append( sizeKb ).append( "</dataSize>\n" ) .append( " </metadata>\n" ) .append( " </dataset>\n" ) .append( "</catalog>" ); String catUri = "Cat.TestReadMetadata.testReadDatasetWithDataSize"; URI catURI = null; try { catURI = new URI( catUri ); } catch ( URISyntaxException e ) { fail( "URISyntaxException: " + e.getMessage() ); return; } InvCatalogFactory fac = InvCatalogFactory.getDefaultFactory( false ); InvCatalogImpl cat = fac.readXML( catAsString.toString(), catURI ); InvDatasetImpl ds = (InvDatasetImpl) cat.getDatasets().get( 0 ); double d = ds.getDataSize(); assertTrue( "Size of data <" + d + "> not as expected <" + sizeKb + ">.", d > sizeKb - 0.001 && d < sizeKb + 0.001 ); }
diff --git a/modules/cpr/src/main/java/org/atmosphere/cpr/AsynchronousProcessor.java b/modules/cpr/src/main/java/org/atmosphere/cpr/AsynchronousProcessor.java index 04a52b8ed..25acfdf41 100755 --- a/modules/cpr/src/main/java/org/atmosphere/cpr/AsynchronousProcessor.java +++ b/modules/cpr/src/main/java/org/atmosphere/cpr/AsynchronousProcessor.java @@ -1,459 +1,454 @@ /* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2007-2008 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. * */ package org.atmosphere.cpr; import org.atmosphere.cpr.AtmosphereServlet.Action; import org.atmosphere.cpr.AtmosphereServlet.AtmosphereConfig; import org.atmosphere.cpr.AtmosphereServlet.AtmosphereHandlerWrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * Base class which implement the semantics of suspending and resuming of a * Comet Request. * * @author Jeanfrancois Arcand */ public abstract class AsynchronousProcessor implements CometSupport<AtmosphereResourceImpl> { private static final Logger logger = LoggerFactory.getLogger(AsynchronousProcessor.class); protected static final Action timedoutAction = new Action(Action.TYPE.TIMEOUT); protected static final Action cancelledAction = new Action(Action.TYPE.CANCELLED); private static final int DEFAULT_SESSION_TIMEOUT = 1800; protected final AtmosphereConfig config; protected final ConcurrentHashMap<HttpServletRequest, AtmosphereResource<HttpServletRequest, HttpServletResponse>> aliveRequests = new ConcurrentHashMap<HttpServletRequest, AtmosphereResource<HttpServletRequest, HttpServletResponse>>(); private final ScheduledExecutorService closedDetector = Executors.newScheduledThreadPool(1); public AsynchronousProcessor(AtmosphereConfig config) { this.config = config; } @Override public void init(ServletConfig sc) throws ServletException { String maxInactive = sc.getInitParameter(MAX_INACTIVE) != null ? sc.getInitParameter(MAX_INACTIVE) : config.getInitParameter(MAX_INACTIVE); if (maxInactive != null) { final long maxInactiveTime = Long.parseLong(maxInactive); if (maxInactiveTime <= 0) return; closedDetector.scheduleAtFixedRate(new Runnable() { public void run() { for (HttpServletRequest req : aliveRequests.keySet()) { long l = (Long) req.getAttribute(MAX_INACTIVE); if (l > 0 && System.currentTimeMillis() - l > maxInactiveTime) { try { cancelled(req, aliveRequests.get(req).getResponse()); req.setAttribute(MAX_INACTIVE, (long) -1); } catch (IOException e) { } catch (ServletException e) { } } } } }, 0, 1, TimeUnit.SECONDS); } } /** * Is {@link HttpSession} supported * * @return true if supported */ protected boolean supportSession() { return config.isSupportSession(); } /** * Return the container's name. */ public String getContainerName() { return config.getServletConfig().getServletContext().getServerInfo(); } /** * All proprietary Comet based {@link Servlet} must invoke the suspended * method when the first request comes in. The returned value, of type * {@link AtmosphereServlet.Action}, tells the proprietary Comet {@link Servlet} * to suspended or not the current {@link HttpServletResponse}. * * @param request the {@link HttpServletRequest} * @param response the {@link HttpServletResponse} * @return action the Action operation. * @throws java.io.IOException * @throws javax.servlet.ServletException */ public Action suspended(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { return action(request, response); } /** * Invoke the {@link AtmosphereHandler#onRequest} method. * * @param req the {@link HttpServletRequest} * @param res the {@link HttpServletResponse} * @return action the Action operation. * @throws java.io.IOException * @throws javax.servlet.ServletException */ Action action(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { boolean webSocketEnabled = false; if (req.getHeaders("Connection") != null && req.getHeaders("Connection").hasMoreElements()) { String[] e = req.getHeaders("Connection").nextElement().split(","); for (String upgrade : e) { if (upgrade.equalsIgnoreCase("Upgrade")) { webSocketEnabled = true; break; } } } if (webSocketEnabled && !supportWebSocket()) { res.setStatus(501); res.addHeader("X-Atmosphere-error", "Websocket protocol not supported"); res.flushBuffer(); return new Action(); } if (config.handlers().isEmpty()) { logger.error("No AtmosphereHandler found. Make sure you define it inside META-INF/atmosphere.xml"); throw new ServletException("No AtmosphereHandler found. Make sure you define it inside META-INF/atmosphere.xml"); } if (supportSession()) { // Create the session needed to support the Resume // operation from disparate requests. HttpSession session = req.getSession(true); // Do not allow times out. if (session.getMaxInactiveInterval() == DEFAULT_SESSION_TIMEOUT) { session.setMaxInactiveInterval(-1); } } req.setAttribute(AtmosphereServlet.SUPPORT_SESSION, supportSession()); AtmosphereHandlerWrapper handlerWrapper = map(req); - AtmosphereResourceImpl resource = null; - if (req.getAttribute(AtmosphereServlet.ATMOSPHERE_RESOURCE) == null) { - resource = new AtmosphereResourceImpl(config, handlerWrapper.broadcaster, req, res, this, handlerWrapper.atmosphereHandler); - } else { - resource = (AtmosphereResourceImpl) req.getAttribute(AtmosphereServlet.ATMOSPHERE_RESOURCE); - } + AtmosphereResourceImpl resource = new AtmosphereResourceImpl(config, handlerWrapper.broadcaster, req, res, this, handlerWrapper.atmosphereHandler); handlerWrapper.broadcaster.getBroadcasterConfig().setAtmosphereConfig(config); req.setAttribute(AtmosphereServlet.ATMOSPHERE_RESOURCE, resource); req.setAttribute(AtmosphereServlet.ATMOSPHERE_HANDLER, handlerWrapper.atmosphereHandler); try { handlerWrapper.atmosphereHandler.onRequest(resource); } catch (IOException t) { resource.onThrowable(t); throw t; } if (resource.getAtmosphereResourceEvent().isSuspended()) { req.setAttribute(MAX_INACTIVE, System.currentTimeMillis()); aliveRequests.put(req, resource); } return resource.action(); } /** * {@inheritDoc} */ public void action(AtmosphereResourceImpl r) { aliveRequests.remove(r.getRequest()); } /** * Return the {@link AtmosphereHandler} mapped to the passed servlet-path. * * @param req the {@link HttpServletResponse} * @return the {@link AtmosphereHandler} mapped to the passed servlet-path. * @throws javax.servlet.ServletException */ protected AtmosphereHandlerWrapper map(HttpServletRequest req) throws ServletException { String path = req.getServletPath(); if (path == null || path.length() == 0) { path = "/"; } AtmosphereHandlerWrapper atmosphereHandlerWrapper = config.handlers().get(path); if (atmosphereHandlerWrapper == null) { // Try the /* if (!path.endsWith("/")) { path += "/*"; } else { path += "*"; } atmosphereHandlerWrapper = config.handlers().get(path); if (atmosphereHandlerWrapper == null) { atmosphereHandlerWrapper = config.handlers().get("/*"); if (atmosphereHandlerWrapper == null) { if (req.getPathInfo() != null) { // Try appending the pathInfo path = req.getServletPath() + req.getPathInfo(); } atmosphereHandlerWrapper = config.handlers().get(path); if (atmosphereHandlerWrapper == null) { // Last chance if (!path.endsWith("/")) { path += "/*"; } else { path += "*"; } // Try appending the pathInfo atmosphereHandlerWrapper = config.handlers().get(path); if (atmosphereHandlerWrapper == null) { logger.warn("No AtmosphereHandler maps request for {}", path); for (String m : config.handlers().keySet()) { logger.warn("\tAtmosphereHandler registered: {}", m); } throw new ServletException("No AtmosphereHandler maps request for " + path); } } } } } config.getBroadcasterFactory().add(atmosphereHandlerWrapper.broadcaster, atmosphereHandlerWrapper.broadcaster.getID()); return atmosphereHandlerWrapper; } /** * All proprietary Comet based {@link Servlet} must invoke the resume * method when the Atmosphere's application decide to resume the {@link HttpServletResponse}. * The returned value, of type * {@link AtmosphereServlet.Action}, tells the proprietary Comet {@link Servlet} * to resume (again), suspended or do nothing with the current {@link HttpServletResponse}. * * @param request the {@link HttpServletRequest} * @param response the {@link HttpServletResponse} * @return action the Action operation. * @throws java.io.IOException * @throws javax.servlet.ServletException */ public Action resumed(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { logger.debug("(resumed) invoked:\n HttpServletRequest: {}\n HttpServletResponse: {}", request, response); return action(request, response); } /** * All proprietary Comet based {@link Servlet} must invoke the timedout * method when the underlying WebServer time out the {@link HttpServletResponse}. * The returned value, of type * {@link AtmosphereServlet.Action}, tells the proprietary Comet {@link Servlet} * to resume (again), suspended or do nothing with the current {@link HttpServletResponse}. * * @param request the {@link HttpServletRequest} * @param response the {@link HttpServletResponse} * @return action the Action operation. * @throws java.io.IOException * @throws javax.servlet.ServletException */ public Action timedout(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { AtmosphereResourceImpl re; long l = (Long) request.getAttribute(MAX_INACTIVE); if (l == -1) { // The closedDetector closed the connection. return timedoutAction; } request.setAttribute(MAX_INACTIVE, (long) -1); // Something went wrong. if (request == null || response == null) { logger.warn("Invalid Request/Response: {}/{}", request, response); return timedoutAction; } re = (AtmosphereResourceImpl) request.getAttribute(AtmosphereServlet.ATMOSPHERE_RESOURCE); if (re != null) { re.getAtmosphereResourceEvent().setIsResumedOnTimeout(true); Broadcaster b = re.getBroadcaster(); if (b instanceof DefaultBroadcaster) { ((DefaultBroadcaster) b).broadcastOnResume(re); } if (re.getRequest().getAttribute(AtmosphereServlet.RESUMED_ON_TIMEOUT) != null) { re.getAtmosphereResourceEvent().setIsResumedOnTimeout( (Boolean) re.getRequest().getAttribute(AtmosphereServlet.RESUMED_ON_TIMEOUT)); } invokeAtmosphereHandler(re); } return timedoutAction; } void invokeAtmosphereHandler(AtmosphereResourceImpl r) throws IOException { HttpServletRequest req = r.getRequest(); HttpServletResponse response = r.getResponse(); String disableOnEvent = r.getAtmosphereConfig().getInitParameter(AtmosphereServlet.DISABLE_ONSTATE_EVENT); try { if (!r.getResponse().equals(response)) { logger.warn("Invalid response: {}", response); } else if (disableOnEvent == null || !disableOnEvent.equals(String.valueOf(true))) { AtmosphereHandler<HttpServletRequest, HttpServletResponse> atmosphereHandler = (AtmosphereHandler<HttpServletRequest, HttpServletResponse>) req.getAttribute(AtmosphereServlet.ATMOSPHERE_HANDLER); atmosphereHandler.onStateChange(r.getAtmosphereResourceEvent()); } else { r.getResponse().flushBuffer(); } } catch (IOException ex) { try { r.onThrowable(ex); } catch (Throwable t) { logger.warn("failed calling onThrowable()", ex); } } finally { try { aliveRequests.remove(req); r.notifyListeners(); } finally { destroyResource(r); } } } private void destroyResource(AtmosphereResourceImpl r) { r.removeEventListeners(); try { r.getBroadcaster().removeAtmosphereResource(r); } catch (IllegalStateException ex) { logger.trace(ex.getMessage(), ex); } if (BroadcasterFactory.getDefault() != null) { BroadcasterFactory.getDefault().removeAllAtmosphereResource(r); } } /** * All proprietary Comet based {@link Servlet} must invoke the cancelled * method when the underlying WebServer detect that the client closed * the connection. * * @param req the {@link HttpServletRequest} * @param res the {@link HttpServletResponse} * @return action the Action operation. * @throws java.io.IOException * @throws javax.servlet.ServletException */ public Action cancelled(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { AtmosphereResourceImpl re = null; long l = (Long) req.getAttribute(MAX_INACTIVE); if (l == -1) { // The closedDetector closed the connection. return timedoutAction; } req.setAttribute(MAX_INACTIVE, (long) -1); try { re = (AtmosphereResourceImpl) req.getAttribute(AtmosphereServlet.ATMOSPHERE_RESOURCE); if (re != null) { re.getAtmosphereResourceEvent().setCancelled(true); invokeAtmosphereHandler(re); re.setIsInScope(false); } } catch (Throwable ex) { // Something wrong happenned, ignore the exception logger.debug("failed to cancel resource: " + re, ex); } finally { try { aliveRequests.remove(req); if (re != null) { re.notifyListeners(); } } finally { if (re != null) { destroyResource(re); } } } return cancelledAction; } void shutdown() { closedDetector.shutdownNow(); for (AtmosphereResource<HttpServletRequest, HttpServletResponse> resource : aliveRequests.values()) { try { resource.resume(); } catch (Throwable t) { // Something wrong happenned, ignore the exception logger.debug("failed on resume: " + resource, t); } } } public boolean supportWebSocket() { return false; } }
true
true
Action action(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { boolean webSocketEnabled = false; if (req.getHeaders("Connection") != null && req.getHeaders("Connection").hasMoreElements()) { String[] e = req.getHeaders("Connection").nextElement().split(","); for (String upgrade : e) { if (upgrade.equalsIgnoreCase("Upgrade")) { webSocketEnabled = true; break; } } } if (webSocketEnabled && !supportWebSocket()) { res.setStatus(501); res.addHeader("X-Atmosphere-error", "Websocket protocol not supported"); res.flushBuffer(); return new Action(); } if (config.handlers().isEmpty()) { logger.error("No AtmosphereHandler found. Make sure you define it inside META-INF/atmosphere.xml"); throw new ServletException("No AtmosphereHandler found. Make sure you define it inside META-INF/atmosphere.xml"); } if (supportSession()) { // Create the session needed to support the Resume // operation from disparate requests. HttpSession session = req.getSession(true); // Do not allow times out. if (session.getMaxInactiveInterval() == DEFAULT_SESSION_TIMEOUT) { session.setMaxInactiveInterval(-1); } } req.setAttribute(AtmosphereServlet.SUPPORT_SESSION, supportSession()); AtmosphereHandlerWrapper handlerWrapper = map(req); AtmosphereResourceImpl resource = null; if (req.getAttribute(AtmosphereServlet.ATMOSPHERE_RESOURCE) == null) { resource = new AtmosphereResourceImpl(config, handlerWrapper.broadcaster, req, res, this, handlerWrapper.atmosphereHandler); } else { resource = (AtmosphereResourceImpl) req.getAttribute(AtmosphereServlet.ATMOSPHERE_RESOURCE); } handlerWrapper.broadcaster.getBroadcasterConfig().setAtmosphereConfig(config); req.setAttribute(AtmosphereServlet.ATMOSPHERE_RESOURCE, resource); req.setAttribute(AtmosphereServlet.ATMOSPHERE_HANDLER, handlerWrapper.atmosphereHandler); try { handlerWrapper.atmosphereHandler.onRequest(resource); } catch (IOException t) { resource.onThrowable(t); throw t; } if (resource.getAtmosphereResourceEvent().isSuspended()) { req.setAttribute(MAX_INACTIVE, System.currentTimeMillis()); aliveRequests.put(req, resource); } return resource.action(); }
Action action(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { boolean webSocketEnabled = false; if (req.getHeaders("Connection") != null && req.getHeaders("Connection").hasMoreElements()) { String[] e = req.getHeaders("Connection").nextElement().split(","); for (String upgrade : e) { if (upgrade.equalsIgnoreCase("Upgrade")) { webSocketEnabled = true; break; } } } if (webSocketEnabled && !supportWebSocket()) { res.setStatus(501); res.addHeader("X-Atmosphere-error", "Websocket protocol not supported"); res.flushBuffer(); return new Action(); } if (config.handlers().isEmpty()) { logger.error("No AtmosphereHandler found. Make sure you define it inside META-INF/atmosphere.xml"); throw new ServletException("No AtmosphereHandler found. Make sure you define it inside META-INF/atmosphere.xml"); } if (supportSession()) { // Create the session needed to support the Resume // operation from disparate requests. HttpSession session = req.getSession(true); // Do not allow times out. if (session.getMaxInactiveInterval() == DEFAULT_SESSION_TIMEOUT) { session.setMaxInactiveInterval(-1); } } req.setAttribute(AtmosphereServlet.SUPPORT_SESSION, supportSession()); AtmosphereHandlerWrapper handlerWrapper = map(req); AtmosphereResourceImpl resource = new AtmosphereResourceImpl(config, handlerWrapper.broadcaster, req, res, this, handlerWrapper.atmosphereHandler); handlerWrapper.broadcaster.getBroadcasterConfig().setAtmosphereConfig(config); req.setAttribute(AtmosphereServlet.ATMOSPHERE_RESOURCE, resource); req.setAttribute(AtmosphereServlet.ATMOSPHERE_HANDLER, handlerWrapper.atmosphereHandler); try { handlerWrapper.atmosphereHandler.onRequest(resource); } catch (IOException t) { resource.onThrowable(t); throw t; } if (resource.getAtmosphereResourceEvent().isSuspended()) { req.setAttribute(MAX_INACTIVE, System.currentTimeMillis()); aliveRequests.put(req, resource); } return resource.action(); }
diff --git a/src/main/java/com/angelini/fly/LayoutTemplater.java b/src/main/java/com/angelini/fly/LayoutTemplater.java index 36895d1..7618745 100644 --- a/src/main/java/com/angelini/fly/LayoutTemplater.java +++ b/src/main/java/com/angelini/fly/LayoutTemplater.java @@ -1,57 +1,57 @@ package com.angelini.fly; import java.io.IOException; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LayoutTemplater extends HttpServlet { private static final long serialVersionUID = 1L; private static final String LAYOUT = "/layout/layout.html"; private static final String COMPONENT = "<script id=\"{{id}}\" type=\"text/template\">" + " \n{{html}}\n" + "</script>"; private String folder; private String layout; private String compString; private Authentication auth; public LayoutTemplater(String folder, Map<String, String> components, Authentication auth) throws IOException { this.folder = folder; this.layout = Utils.readFile(LAYOUT); this.compString = ""; this.auth = auth; for (Map.Entry<String, String> entry : components.entrySet()) { String comp = COMPONENT.replace("{{id}}", entry.getKey().split("\\.")[0]); compString += comp.replace("{{html}}", entry.getValue()); } layout = layout.replace("{{components}}", compString); } protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - if (auth != null && auth.verifySignature(req) != null) { + if (auth != null && auth.verifySignature(req) == null) { resp.sendRedirect(AuthServlet.LOGIN_URL); return; } try { String path = (req.getPathInfo() == "/") ? "/index.html" : req.getPathInfo(); String html = this.layout.replace("{{body}}", Utils.readFile(folder + path)); resp.setStatus(200); resp.getWriter().print(html); } catch (Exception e) { resp.setStatus(404); } } }
true
true
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (auth != null && auth.verifySignature(req) != null) { resp.sendRedirect(AuthServlet.LOGIN_URL); return; } try { String path = (req.getPathInfo() == "/") ? "/index.html" : req.getPathInfo(); String html = this.layout.replace("{{body}}", Utils.readFile(folder + path)); resp.setStatus(200); resp.getWriter().print(html); } catch (Exception e) { resp.setStatus(404); } }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (auth != null && auth.verifySignature(req) == null) { resp.sendRedirect(AuthServlet.LOGIN_URL); return; } try { String path = (req.getPathInfo() == "/") ? "/index.html" : req.getPathInfo(); String html = this.layout.replace("{{body}}", Utils.readFile(folder + path)); resp.setStatus(200); resp.getWriter().print(html); } catch (Exception e) { resp.setStatus(404); } }
diff --git a/sglr-invoker/src/sglr/SGLRInvoker.java b/sglr-invoker/src/sglr/SGLRInvoker.java index 134c0e6..90677c7 100644 --- a/sglr-invoker/src/sglr/SGLRInvoker.java +++ b/sglr-invoker/src/sglr/SGLRInvoker.java @@ -1,272 +1,272 @@ package sglr; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class SGLRInvoker implements Runnable{ private final static String NO_INPUT_PATH = "_noPath_"; private volatile static SGLRInvoker instance = null; private volatile static String baseLibraryPath = null; private final NotifiableLock parserLock = new NotifiableLock(); private final NotifiableLock parserDoneLock = new NotifiableLock(); private volatile boolean running; private ByteBuffer inputString; private int inputStringLength; private String inputPath; private String parseTableName; private byte[] result; private SGLRInvoker(){ super(); running = true; } public static void setBaseLibraryPath(String basePath){ if(basePath == null){ baseLibraryPath = null; return; } if(basePath.endsWith("/")) baseLibraryPath = basePath; else baseLibraryPath = basePath+"/"; } public static void loadLibraries(){ if(baseLibraryPath == null){ // Look in the library path to find the libraries. try{ System.loadLibrary("ATerm"); System.loadLibrary("ConfigAPI"); System.loadLibrary("ErrorAPI"); System.loadLibrary("LocationAPI"); System.loadLibrary("ATB"); System.loadLibrary("mept"); System.loadLibrary("PTMEPT"); System.loadLibrary("ptable"); System.loadLibrary("logging"); System.loadLibrary("statistics"); System.loadLibrary("sglr"); System.loadLibrary("SGLRInvoker"); }catch(UnsatisfiedLinkError ule){ throw new RuntimeException(ule); } }else{ // Look in the given absolute path (OS specific). String osName = System.getProperty("os.name"); - if(osName.equals("Linux")){ // Linux. + if(osName.indexOf("Linux") != -1){ // Linux. try{ System.load(baseLibraryPath+"libCompleteSGLR.so"); }catch(UnsatisfiedLinkError ule){ throw new RuntimeException(ule); } - }else if(osName.startsWith("Mac")){ // Mac. + }else if(osName.indexOf("Mac") != -1 || osName.indexOf("Darwin") != -1){ // Mac. try{ System.load(baseLibraryPath+"libCompleteSGLR.dylib"); }catch(UnsatisfiedLinkError ule){ throw new RuntimeException(ule); } }else if(osName.startsWith("Win")){ // Windows. try{ System.load(baseLibraryPath+"CompleteSGLR.dll"); }catch(UnsatisfiedLinkError ule){ throw new RuntimeException(ule); } }else{ throw new RuntimeException("Unknown OS. Unable to load libraries for SGLR Invoker."); } } } public static SGLRInvoker getInstance(){ if(instance == null){ synchronized(SGLRInvoker.class){ if(instance == null){ // Yes DCL works on volatiles. loadLibraries(); instance = new SGLRInvoker(); Thread parserThread = new Thread(instance); parserThread.setDaemon(true); parserThread.start(); } } } return instance; } public void stop(){ running = false; synchronized(parserLock){ parserLock.notified = true; parserLock.notify(); } } public void run(){ initialize(); while(running){ synchronized(parserLock){ while(!parserLock.notified){ try{ parserLock.wait(); }catch(InterruptedException irex){ // Ignore this; we don't want to know. } if(!running) return; } parserLock.notified = false; } // Invoke the parser. ByteBuffer resultBuffer = parse(); // Construct the result. byte[] data = new byte[resultBuffer.capacity()]; resultBuffer.get(data); result = data; // Cleanup. inputString = null; parseTableName = null; synchronized(parserDoneLock){ parserDoneLock.notified = true; parserDoneLock.notify(); } } } public synchronized byte[] parseFromString(String inputString, String parseTableName){ if(inputString == null) throw new IllegalArgumentException("InputString must not be null."); if(parseTableName == null) throw new IllegalArgumentException("ParseTableName must not be null."); return reallyParse(fillInputStringBufferFromBytes(inputString.getBytes()), NO_INPUT_PATH, parseTableName); } private byte[] buffer = new byte[8192]; // Shared & locked. public synchronized byte[] parseFromStream(InputStream inputStringStream, String parseTableName) throws IOException{ if(inputStringStream == null) throw new IllegalArgumentException("InputStringStream must not be null."); if(parseTableName == null) throw new IllegalArgumentException("ParseTableName must not be null."); ByteArrayOutputStream inputStringData = new ByteArrayOutputStream(); int bytesRead; while((bytesRead = inputStringStream.read(buffer)) != -1){ inputStringData.write(buffer, 0, bytesRead); } return reallyParse(fillInputStringBufferFromBytes(inputStringData.toByteArray()), NO_INPUT_PATH, parseTableName); } public synchronized byte[] parseFromFile(File inputFile, String parseTableName) throws IOException{ if(inputFile == null) throw new IllegalArgumentException("InputFile must not be null."); if(!inputFile.exists()) throw new IllegalArgumentException("InputFile "+inputFile+" does not exist."); if(parseTableName == null) throw new IllegalArgumentException("ParseTableName must not be null."); return reallyParse(fillInputStringBufferFromFile(inputFile), inputFile.getAbsolutePath(), parseTableName); } private ByteBuffer cachedInputStringBuffer = ByteBuffer.allocateDirect(65536); private ByteBuffer getInputStringBuffer(int requiredSize){ int cachedBufferCapacity = cachedInputStringBuffer.capacity(); if(requiredSize > cachedBufferCapacity){ cachedInputStringBuffer = ByteBuffer.allocateDirect(requiredSize); } cachedInputStringBuffer.clear(); return cachedInputStringBuffer; } private ByteBuffer fillInputStringBufferFromBytes(byte[] inputStringData){ ByteBuffer inputStringBuffer = getInputStringBuffer(inputStringData.length); inputStringBuffer.put(inputStringData); inputStringBuffer.flip(); return inputStringBuffer; } private ByteBuffer fillInputStringBufferFromFile(File inputFile) throws IOException{ ByteBuffer inputStringBuffer = getInputStringBuffer((int) inputFile.length()); // If you want to parse something larger then 2GB it won't work anyway. FileInputStream fis = null; try{ fis = new FileInputStream(inputFile); FileChannel fc = fis.getChannel(); fc.read(inputStringBuffer); }finally{ if(fis != null) fis.close(); } inputStringBuffer.flip(); return inputStringBuffer; } private byte[] reallyParse(ByteBuffer inputStringBuffer, String inputPath, String parseTableName){ synchronized(parserDoneLock){ this.inputString = inputStringBuffer; this.inputStringLength = inputStringBuffer.limit(); this.inputPath = inputPath; this.parseTableName = parseTableName; synchronized(parserLock){ parserLock.notified = true; parserLock.notify(); } /* Wait for it. */ while(!parserDoneLock.notified){ try{ parserDoneLock.wait(); }catch(InterruptedException irex){ // Ignore this; we don't want to know. } } parserDoneLock.notified = false; } byte[] parseTree = result; result = null; // Cleanup. return parseTree; } private ByteBuffer getInputString(){ return inputString; } private int getInputStringLength(){ return inputStringLength; } private String getInputPath(){ return inputPath; } private String getParseTableName(){ return parseTableName; } private native void initialize(); private native ByteBuffer parse(); private static class NotifiableLock{ public boolean notified = false; } }
false
true
public static void loadLibraries(){ if(baseLibraryPath == null){ // Look in the library path to find the libraries. try{ System.loadLibrary("ATerm"); System.loadLibrary("ConfigAPI"); System.loadLibrary("ErrorAPI"); System.loadLibrary("LocationAPI"); System.loadLibrary("ATB"); System.loadLibrary("mept"); System.loadLibrary("PTMEPT"); System.loadLibrary("ptable"); System.loadLibrary("logging"); System.loadLibrary("statistics"); System.loadLibrary("sglr"); System.loadLibrary("SGLRInvoker"); }catch(UnsatisfiedLinkError ule){ throw new RuntimeException(ule); } }else{ // Look in the given absolute path (OS specific). String osName = System.getProperty("os.name"); if(osName.equals("Linux")){ // Linux. try{ System.load(baseLibraryPath+"libCompleteSGLR.so"); }catch(UnsatisfiedLinkError ule){ throw new RuntimeException(ule); } }else if(osName.startsWith("Mac")){ // Mac. try{ System.load(baseLibraryPath+"libCompleteSGLR.dylib"); }catch(UnsatisfiedLinkError ule){ throw new RuntimeException(ule); } }else if(osName.startsWith("Win")){ // Windows. try{ System.load(baseLibraryPath+"CompleteSGLR.dll"); }catch(UnsatisfiedLinkError ule){ throw new RuntimeException(ule); } }else{ throw new RuntimeException("Unknown OS. Unable to load libraries for SGLR Invoker."); } } }
public static void loadLibraries(){ if(baseLibraryPath == null){ // Look in the library path to find the libraries. try{ System.loadLibrary("ATerm"); System.loadLibrary("ConfigAPI"); System.loadLibrary("ErrorAPI"); System.loadLibrary("LocationAPI"); System.loadLibrary("ATB"); System.loadLibrary("mept"); System.loadLibrary("PTMEPT"); System.loadLibrary("ptable"); System.loadLibrary("logging"); System.loadLibrary("statistics"); System.loadLibrary("sglr"); System.loadLibrary("SGLRInvoker"); }catch(UnsatisfiedLinkError ule){ throw new RuntimeException(ule); } }else{ // Look in the given absolute path (OS specific). String osName = System.getProperty("os.name"); if(osName.indexOf("Linux") != -1){ // Linux. try{ System.load(baseLibraryPath+"libCompleteSGLR.so"); }catch(UnsatisfiedLinkError ule){ throw new RuntimeException(ule); } }else if(osName.indexOf("Mac") != -1 || osName.indexOf("Darwin") != -1){ // Mac. try{ System.load(baseLibraryPath+"libCompleteSGLR.dylib"); }catch(UnsatisfiedLinkError ule){ throw new RuntimeException(ule); } }else if(osName.startsWith("Win")){ // Windows. try{ System.load(baseLibraryPath+"CompleteSGLR.dll"); }catch(UnsatisfiedLinkError ule){ throw new RuntimeException(ule); } }else{ throw new RuntimeException("Unknown OS. Unable to load libraries for SGLR Invoker."); } } }
diff --git a/src/PageView.java b/src/PageView.java index 377aa55..a7c5266 100644 --- a/src/PageView.java +++ b/src/PageView.java @@ -1,106 +1,108 @@ import java.util.ArrayList; /** * Abstract class to handle a page. * * Options: * s: to select * p: previous page * n: next page * q: to exit * * @author George Coomber and Michael Feist */ abstract public class PageView implements Callback { ArrayList<DatabaseRow> rows; abstract public void view(); abstract public void getRowInfo(String id); public void pageView(int pageSize) { boolean run = true; int pageNumber = 1; int i = 0; while (run) { while (i < pageSize*pageNumber && i < rows.size()) { System.out.println((i + 1) + ": " + rows.get(i).toString()); i++; } System.out.println("\nSearch Result Options"); System.out.println("s: to select"); System.out.println("p: previous page"); System.out.println("n: next page"); System.out.println("q: to exit"); String command = Menu.getKeyBoard(); switch (command.toCharArray()[0]) { case 's': System.out.println("Enter the row number:"); String input = Menu.getKeyBoard(); - Integer adNumber = Integer.valueOf(input); + Integer adNumber = null; - if (adNumber == null) + try { + adNumber = new Integer(input); + } catch (Exception e) { System.out.println("Error: Not an Integer."); - return; + break; } int row = adNumber.intValue(); if (row >= 1 && row <= rows.size()) { getRowInfo(rows.get(row - 1).getID()); } i = pageSize*(pageNumber - 1); break; case 'p': if (pageNumber > 1) { pageNumber--; i = pageSize*(pageNumber - 1); } else { i = pageSize*(pageNumber - 1); } break; case 'n': if (i < rows.size()) { i = pageSize*pageNumber; pageNumber++; } else { i = pageSize*(pageNumber - 1); } break; case 'q': run = false; break; default: i = pageSize*(pageNumber - 1); System.out.println("Error: Unknown command."); break; } } } @Override public int callback() { view(); return Callback.OK; } }
false
true
public void pageView(int pageSize) { boolean run = true; int pageNumber = 1; int i = 0; while (run) { while (i < pageSize*pageNumber && i < rows.size()) { System.out.println((i + 1) + ": " + rows.get(i).toString()); i++; } System.out.println("\nSearch Result Options"); System.out.println("s: to select"); System.out.println("p: previous page"); System.out.println("n: next page"); System.out.println("q: to exit"); String command = Menu.getKeyBoard(); switch (command.toCharArray()[0]) { case 's': System.out.println("Enter the row number:"); String input = Menu.getKeyBoard(); Integer adNumber = Integer.valueOf(input); if (adNumber == null) { System.out.println("Error: Not an Integer."); return; } int row = adNumber.intValue(); if (row >= 1 && row <= rows.size()) { getRowInfo(rows.get(row - 1).getID()); } i = pageSize*(pageNumber - 1); break; case 'p': if (pageNumber > 1) { pageNumber--; i = pageSize*(pageNumber - 1); } else { i = pageSize*(pageNumber - 1); } break; case 'n': if (i < rows.size()) { i = pageSize*pageNumber; pageNumber++; } else { i = pageSize*(pageNumber - 1); } break; case 'q': run = false; break; default: i = pageSize*(pageNumber - 1); System.out.println("Error: Unknown command."); break; } } }
public void pageView(int pageSize) { boolean run = true; int pageNumber = 1; int i = 0; while (run) { while (i < pageSize*pageNumber && i < rows.size()) { System.out.println((i + 1) + ": " + rows.get(i).toString()); i++; } System.out.println("\nSearch Result Options"); System.out.println("s: to select"); System.out.println("p: previous page"); System.out.println("n: next page"); System.out.println("q: to exit"); String command = Menu.getKeyBoard(); switch (command.toCharArray()[0]) { case 's': System.out.println("Enter the row number:"); String input = Menu.getKeyBoard(); Integer adNumber = null; try { adNumber = new Integer(input); } catch (Exception e) { System.out.println("Error: Not an Integer."); break; } int row = adNumber.intValue(); if (row >= 1 && row <= rows.size()) { getRowInfo(rows.get(row - 1).getID()); } i = pageSize*(pageNumber - 1); break; case 'p': if (pageNumber > 1) { pageNumber--; i = pageSize*(pageNumber - 1); } else { i = pageSize*(pageNumber - 1); } break; case 'n': if (i < rows.size()) { i = pageSize*pageNumber; pageNumber++; } else { i = pageSize*(pageNumber - 1); } break; case 'q': run = false; break; default: i = pageSize*(pageNumber - 1); System.out.println("Error: Unknown command."); break; } } }
diff --git a/src/web/org/codehaus/groovy/grails/web/mapping/RegexUrlMapping.java b/src/web/org/codehaus/groovy/grails/web/mapping/RegexUrlMapping.java index 5910343e1..483402b04 100644 --- a/src/web/org/codehaus/groovy/grails/web/mapping/RegexUrlMapping.java +++ b/src/web/org/codehaus/groovy/grails/web/mapping/RegexUrlMapping.java @@ -1,504 +1,504 @@ /* Copyright 2004-2005 Graeme Rocher * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.web.mapping; import groovy.lang.Closure; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.codehaus.groovy.grails.commons.GrailsControllerClass; import org.codehaus.groovy.grails.validation.ConstrainedProperty; import org.codehaus.groovy.grails.web.mapping.exceptions.UrlMappingException; import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest; import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException; import org.springframework.validation.Errors; import org.springframework.validation.MapBindingResult; import org.springframework.web.context.request.RequestContextHolder; import javax.servlet.ServletContext; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * <p>A UrlMapping implementation that takes a Grails URL pattern and turns it into a regex matcher so that * URLs can be matched and information captured from the match.</p> * <p/> * <p>A Grails URL pattern is not a regex, but is an extension to the form defined by Apache Ant and used by * Spring AntPathMatcher. Unlike regular Ant paths Grails URL patterns allow for capturing groups in the form:</p> * <p/> * <code>/blog/(*)/**</code> * <p/> * <p>The parenthesis define a capturing group. This implementation transforms regular Ant paths into regular expressions * that are able to use capturing groups</p> * * @author Graeme Rocher * @see org.springframework.util.AntPathMatcher * @since 0.5 * <p/> * <p/> * Created: Feb 28, 2007 * Time: 6:12:52 PM */ public class RegexUrlMapping extends AbstractUrlMapping implements UrlMapping { private Pattern[] patterns; private UrlMappingData urlData; private static final String WILDCARD = "*"; private static final String CAPTURED_WILDCARD = "(*)"; private static final String SLASH = "/"; private static final char QUESTION_MARK = '?'; private static final String ENTITY_AMPERSAND = "&amp;"; private static final char AMPERSAND = '&'; private static final String DOUBLE_WILDCARD = "**"; private static final String DEFAULT_ENCODING = "UTF-8"; private static final String CAPTURED_DOUBLE_WILDCARD = "(**)"; private static final Log LOG = LogFactory.getLog(RegexUrlMapping.class); /** * Constructs a new RegexUrlMapping for the given pattern, controller name, action name and constraints. * * @param data An instance of the UrlMappingData class that holds necessary information of the URL mapping * @param controllerName The name of the controller the URL maps to (required) * @param actionName The name of the action the URL maps to * @param viewName The name of the view as an alternative to the name of the action. If the action is specified it takes precedence over the view name during mapping * @param constraints A list of ConstrainedProperty instances that relate to tokens in the URL * @param servletContext * @see org.codehaus.groovy.grails.validation.ConstrainedProperty */ public RegexUrlMapping(UrlMappingData data, Object controllerName, Object actionName, Object viewName, ConstrainedProperty[] constraints, ServletContext servletContext) { super(controllerName, actionName, viewName, constraints != null ? constraints : new ConstrainedProperty[0], servletContext); parse(data, constraints); } private void parse(UrlMappingData data, ConstrainedProperty[] constraints) { if (data == null) throw new IllegalArgumentException("Argument [pattern] cannot be null"); String[] urls = data.getLogicalUrls(); this.urlData = data; this.patterns = new Pattern[urls.length]; for (int i = 0; i < urls.length; i++) { String url = urls[i]; Pattern pattern = convertToRegex(url); if (pattern == null) throw new IllegalStateException("Cannot use null pattern in regular expression mapping for url [" + data.getUrlPattern() + "]"); this.patterns[i] = pattern; } if (constraints != null) { for (int i = 0; i < constraints.length; i++) { ConstrainedProperty constraint = constraints[i]; if (data.isOptional(i)) { constraint.setNullable(true); } } } } /** * Converst a Grails URL provides via the UrlMappingData interface to a regular expression * * @param url The URL to convert * @return A regex Pattern objet */ protected Pattern convertToRegex(String url) { Pattern regex; String pattern = null; try { pattern = "^" + url.replaceAll("([^\\*])\\*([^\\*])", "$1[^/]+$2").replaceAll("([^\\*])\\*$", "$1[^/]+").replaceAll("\\*\\*", ".*"); pattern += "/??$"; regex = Pattern.compile(pattern); } catch (PatternSyntaxException pse) { throw new UrlMappingException("Error evaluating mapping for pattern [" + pattern + "] from Grails URL mappings: " + pse.getMessage(), pse); } return regex; } /** * Matches the given URI and returns a DefaultUrlMappingInfo instance or null * * @param uri The URI to match * @return A UrlMappingInfo instance or null * @see org.codehaus.groovy.grails.web.mapping.UrlMappingInfo */ public UrlMappingInfo match(String uri) { for (int i = 0; i < patterns.length; i++) { Pattern pattern = patterns[i]; Matcher m = pattern.matcher(uri); if (m.matches()) { UrlMappingInfo urlInfo = createUrlMappingInfo(uri, m); if (urlInfo != null) { return urlInfo; } } } return null; } /** * @see org.codehaus.groovy.grails.web.mapping.UrlMapping */ public String createURL(Map parameterValues, String encoding) { return createURLInternal(parameterValues, encoding, true); } private String createURLInternal(Map parameterValues, String encoding, boolean includeContextPath) { if (encoding == null) encoding = "utf-8"; String contextPath = ""; if (includeContextPath) { GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes(); if (webRequest != null) { contextPath = webRequest.getAttributes().getApplicationUri(webRequest.getCurrentRequest()); } } if (parameterValues == null) parameterValues = Collections.EMPTY_MAP; StringBuffer uri = new StringBuffer(contextPath); Set usedParams = new HashSet(); String[] tokens = urlData.getTokens(); int paramIndex = 0; for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; if (CAPTURED_WILDCARD.equals(token) || CAPTURED_DOUBLE_WILDCARD.equals(token)) { ConstrainedProperty prop = this.constraints[paramIndex++]; String propName = prop.getPropertyName(); Object value = parameterValues.get(propName); usedParams.add(propName); if (value == null && !prop.isNullable()) throw new UrlMappingException("Unable to create URL for mapping [" + this + "] and parameters [" + parameterValues + "]. Parameter [" + prop.getPropertyName() + "] is required, but was not specified!"); else if (value == null) break; try { String v = value.toString(); - if (v.contains(SLASH) + if (v.indexOf(SLASH) > -1 && CAPTURED_DOUBLE_WILDCARD.equals(token)) { // individually URL encode path segments if (v.startsWith(SLASH)) { // get rid of leading slash v = v.substring(SLASH.length()); } String[] segs = v.split(SLASH); for (int s = 0; s < segs.length; s++) { String segment = segs[s]; uri.append(SLASH).append(URLEncoder.encode(segment, encoding)); } } else { // original behavior uri.append(SLASH).append(URLEncoder.encode(v, encoding)); } } catch (UnsupportedEncodingException e) { throw new ControllerExecutionException("Error creating URL for parameters [" + parameterValues + "], problem encoding URL part [" + value + "]: " + e.getMessage(), e); } } else { uri.append(SLASH).append(token); } } populateParameterList(parameterValues, encoding, uri, usedParams); if (LOG.isDebugEnabled()) { LOG.debug("Created reverse URL mapping [" + uri.toString() + "] for parameters [" + parameterValues + "]"); } return uri.toString(); } public String createURL(Map parameterValues, String encoding, String fragment) { String url = createURL(parameterValues, encoding); return createUrlWithFragment(url, fragment, encoding); } public String createURL(String controller, String action, Map parameterValues, String encoding) { return createURLInternal(controller, action, parameterValues, encoding, true); } private String createURLInternal(String controller, String action, Map parameterValues, String encoding, boolean includeContextPath) { if (parameterValues == null) parameterValues = new HashMap(); boolean hasController = !StringUtils.isBlank(controller); boolean hasAction = !StringUtils.isBlank(action); try { if (hasController) parameterValues.put(CONTROLLER, controller); if (hasAction) parameterValues.put(ACTION, action); return createURLInternal(parameterValues, encoding, includeContextPath); } finally { if (hasController) parameterValues.remove(CONTROLLER); if (hasAction) parameterValues.remove(ACTION); } } public String createRelativeURL(String controller, String action, Map parameterValues, String encoding) { return createURLInternal(controller, action, parameterValues, encoding, false); } public String createURL(String controller, String action, Map parameterValues, String encoding, String fragment) { String url = createURL(controller, action, parameterValues, encoding); return createUrlWithFragment(url, fragment, encoding); } private String createUrlWithFragment(String url, String fragment, String encoding) { if (fragment != null) { // A 'null' encoding will cause an exception, so default to 'UTF-8'. if (encoding == null) { encoding = DEFAULT_ENCODING; } try { return url + '#' + URLEncoder.encode(fragment, encoding); } catch (UnsupportedEncodingException ex) { throw new ControllerExecutionException("Error creating URL [" + url + "], problem encoding URL fragment [" + fragment + "]: " + ex.getMessage(), ex); } } else { return url; } } private void populateParameterList(Map parameterValues, String encoding, StringBuffer uri, Set usedParams) { boolean addedParams = false; usedParams.add("controller"); usedParams.add("action"); // A 'null' encoding will cause an exception, so default to 'UTF-8'. if (encoding == null) { encoding = DEFAULT_ENCODING; } for (Iterator i = parameterValues.keySet().iterator(); i.hasNext();) { String name = i.next().toString(); if (!usedParams.contains(name)) { if (!addedParams) { uri.append(QUESTION_MARK); addedParams = true; } else { uri.append(AMPERSAND); } Object value = parameterValues.get(name); if (value != null && value instanceof Collection) { Collection multiValues = (Collection) value; for (Iterator j = multiValues.iterator(); j.hasNext();) { Object o = j.next(); appendValueToURI(encoding, uri, name, o); if (j.hasNext()) { uri.append(AMPERSAND); } } } else if (value != null && value.getClass().isArray()) { Object[] multiValues = (Object[]) value; for (int j = 0; j < multiValues.length; j++) { Object o = multiValues[j]; appendValueToURI(encoding, uri, name, o); if (j + 1 < multiValues.length) { uri.append(AMPERSAND); } } } else { appendValueToURI(encoding, uri, name, value); } } } } private void appendValueToURI(String encoding, StringBuffer uri, String name, Object value) { try { uri.append(URLEncoder.encode(name, encoding)).append('=') .append(URLEncoder.encode(value != null ? value.toString() : "", encoding)); } catch (UnsupportedEncodingException e) { throw new ControllerExecutionException("Error redirecting request for url [" + name + ":" + value + "]: " + e.getMessage(), e); } } public UrlMappingData getUrlData() { return this.urlData; } private UrlMappingInfo createUrlMappingInfo(String uri, Matcher m) { Map params = new HashMap(); Errors errors = new MapBindingResult(params, "urlMapping"); String lastGroup = null; for (int i = 0; i < m.groupCount(); i++) { lastGroup = m.group(i + 1); int j = lastGroup.indexOf('?'); if (j > -1) { lastGroup = lastGroup.substring(0, j); } if (constraints.length > i) { ConstrainedProperty cp = constraints[i]; cp.validate(this, lastGroup, errors); if (errors.hasErrors()) return null; else { params.put(cp.getPropertyName(), lastGroup); } } } if (lastGroup != null) { String remainingUri = uri.substring(uri.lastIndexOf(lastGroup) + lastGroup.length()); if (remainingUri.length() > 0) { if (remainingUri.startsWith(SLASH)) remainingUri = remainingUri.substring(1); String[] tokens = remainingUri.split(SLASH); for (int i = 0; i < tokens.length; i = i + 2) { String token = tokens[i]; if ((i + 1) < tokens.length) { params.put(token, tokens[i + 1]); } } } } for (Iterator i = this.parameterValues.keySet().iterator(); i.hasNext();) { Object key = i.next(); params.put(key, this.parameterValues.get(key)); } if (controllerName == null) { this.controllerName = createRuntimeConstraintEvaluator(GrailsControllerClass.CONTROLLER, this.constraints); } if (actionName == null) { this.actionName = createRuntimeConstraintEvaluator(GrailsControllerClass.ACTION, this.constraints); } if (viewName == null) { this.viewName = createRuntimeConstraintEvaluator(GrailsControllerClass.VIEW, this.constraints); } if (viewName != null && this.controllerName == null) { return new DefaultUrlMappingInfo(viewName, params, this.urlData, servletContext); } else { return new DefaultUrlMappingInfo(this.controllerName, this.actionName, getViewName(), params, this.urlData, servletContext); } } /** * This method will look for a constraint for the given name and return a closure that when executed will * attempt to evaluate its value from the bound request parameters at runtime. * * @param name The name of the constrained property * @param constraints The array of current ConstrainedProperty instances * @return Either a Closure or null */ private Object createRuntimeConstraintEvaluator(final String name, ConstrainedProperty[] constraints) { if (constraints == null) return null; for (int i = 0; i < constraints.length; i++) { ConstrainedProperty constraint = constraints[i]; if (constraint.getPropertyName().equals(name)) { return new Closure(this) { public Object call(Object[] objects) { GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes(); return webRequest.getParams().get(name); } }; } } return null; } public String[] getLogicalMappings() { return this.urlData.getLogicalUrls(); } /** * Compares this UrlMapping instance with the specified UrlMapping instance and deals with URL mapping precedence rules. * * @param o An instance of the UrlMapping interface * @return 1 if this UrlMapping should match before the specified UrlMapping. 0 if they are equal or -1 if this UrlMapping should match after the given UrlMapping */ public int compareTo(Object o) { if (!(o instanceof UrlMapping)) throw new IllegalArgumentException("Cannot compare with Object [" + o + "]. It is not an instance of UrlMapping!"); UrlMapping other = (UrlMapping) o; String[] otherTokens = other .getUrlData() .getTokens(); String[] tokens = getUrlData().getTokens(); if (isWildcard(this) && !isWildcard(other)) return -1; if (!isWildcard(this) && isWildcard(other)) return 1; if (tokens.length < otherTokens.length) { return -1; } else if (tokens.length > otherTokens.length) { return 1; } int result = 0; for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; if (otherTokens.length > i) { String otherToken = otherTokens[i]; if (isWildcard(token) && !isWildcard(otherToken)) { result = -1; break; } else if (!isWildcard(token) && isWildcard(otherToken)) { result = 1; break; } } else { break; } } return result; } private boolean isWildcard(UrlMapping mapping) { String[] tokens = mapping.getUrlData().getTokens(); for (int i = 0; i < tokens.length; i++) { if (isWildcard(tokens[i])) return true; } return false; } private boolean isWildcard(String token) { return WILDCARD.equals(token) || CAPTURED_WILDCARD.equals(token) || DOUBLE_WILDCARD.equals(token) || CAPTURED_DOUBLE_WILDCARD.equals(token); } public String toString() { return this.urlData.getUrlPattern(); } }
true
true
private String createURLInternal(Map parameterValues, String encoding, boolean includeContextPath) { if (encoding == null) encoding = "utf-8"; String contextPath = ""; if (includeContextPath) { GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes(); if (webRequest != null) { contextPath = webRequest.getAttributes().getApplicationUri(webRequest.getCurrentRequest()); } } if (parameterValues == null) parameterValues = Collections.EMPTY_MAP; StringBuffer uri = new StringBuffer(contextPath); Set usedParams = new HashSet(); String[] tokens = urlData.getTokens(); int paramIndex = 0; for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; if (CAPTURED_WILDCARD.equals(token) || CAPTURED_DOUBLE_WILDCARD.equals(token)) { ConstrainedProperty prop = this.constraints[paramIndex++]; String propName = prop.getPropertyName(); Object value = parameterValues.get(propName); usedParams.add(propName); if (value == null && !prop.isNullable()) throw new UrlMappingException("Unable to create URL for mapping [" + this + "] and parameters [" + parameterValues + "]. Parameter [" + prop.getPropertyName() + "] is required, but was not specified!"); else if (value == null) break; try { String v = value.toString(); if (v.contains(SLASH) && CAPTURED_DOUBLE_WILDCARD.equals(token)) { // individually URL encode path segments if (v.startsWith(SLASH)) { // get rid of leading slash v = v.substring(SLASH.length()); } String[] segs = v.split(SLASH); for (int s = 0; s < segs.length; s++) { String segment = segs[s]; uri.append(SLASH).append(URLEncoder.encode(segment, encoding)); } } else { // original behavior uri.append(SLASH).append(URLEncoder.encode(v, encoding)); } } catch (UnsupportedEncodingException e) { throw new ControllerExecutionException("Error creating URL for parameters [" + parameterValues + "], problem encoding URL part [" + value + "]: " + e.getMessage(), e); } } else { uri.append(SLASH).append(token); } } populateParameterList(parameterValues, encoding, uri, usedParams); if (LOG.isDebugEnabled()) { LOG.debug("Created reverse URL mapping [" + uri.toString() + "] for parameters [" + parameterValues + "]"); } return uri.toString(); }
private String createURLInternal(Map parameterValues, String encoding, boolean includeContextPath) { if (encoding == null) encoding = "utf-8"; String contextPath = ""; if (includeContextPath) { GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes(); if (webRequest != null) { contextPath = webRequest.getAttributes().getApplicationUri(webRequest.getCurrentRequest()); } } if (parameterValues == null) parameterValues = Collections.EMPTY_MAP; StringBuffer uri = new StringBuffer(contextPath); Set usedParams = new HashSet(); String[] tokens = urlData.getTokens(); int paramIndex = 0; for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; if (CAPTURED_WILDCARD.equals(token) || CAPTURED_DOUBLE_WILDCARD.equals(token)) { ConstrainedProperty prop = this.constraints[paramIndex++]; String propName = prop.getPropertyName(); Object value = parameterValues.get(propName); usedParams.add(propName); if (value == null && !prop.isNullable()) throw new UrlMappingException("Unable to create URL for mapping [" + this + "] and parameters [" + parameterValues + "]. Parameter [" + prop.getPropertyName() + "] is required, but was not specified!"); else if (value == null) break; try { String v = value.toString(); if (v.indexOf(SLASH) > -1 && CAPTURED_DOUBLE_WILDCARD.equals(token)) { // individually URL encode path segments if (v.startsWith(SLASH)) { // get rid of leading slash v = v.substring(SLASH.length()); } String[] segs = v.split(SLASH); for (int s = 0; s < segs.length; s++) { String segment = segs[s]; uri.append(SLASH).append(URLEncoder.encode(segment, encoding)); } } else { // original behavior uri.append(SLASH).append(URLEncoder.encode(v, encoding)); } } catch (UnsupportedEncodingException e) { throw new ControllerExecutionException("Error creating URL for parameters [" + parameterValues + "], problem encoding URL part [" + value + "]: " + e.getMessage(), e); } } else { uri.append(SLASH).append(token); } } populateParameterList(parameterValues, encoding, uri, usedParams); if (LOG.isDebugEnabled()) { LOG.debug("Created reverse URL mapping [" + uri.toString() + "] for parameters [" + parameterValues + "]"); } return uri.toString(); }
diff --git a/src/net/daboross/bukkitdev/playerdata/PlayerData.java b/src/net/daboross/bukkitdev/playerdata/PlayerData.java index e67e73a..c9214fb 100644 --- a/src/net/daboross/bukkitdev/playerdata/PlayerData.java +++ b/src/net/daboross/bukkitdev/playerdata/PlayerData.java @@ -1,218 +1,216 @@ package net.daboross.bukkitdev.playerdata; import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import net.daboross.bukkitdev.playerdata.metrics.Metrics; import net.milkbowl.vault.permission.Permission; import org.bukkit.Bukkit; import org.bukkit.command.PluginCommand; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; /** * PlayerData Plugin Made By DaboRoss * * @author daboross */ public final class PlayerData extends JavaPlugin { private static PlayerData currentInstance; private static boolean isVaultLoaded; private static Permission permissionHandler; private PDataHandler playerDataHandler; private PlayerDataHandler handler; private PlayerDataEventListener eventListener; private Metrics metrics; private PlayerDataCustomMetrics pdcm; /** * */ @Override public void onEnable() { currentInstance = this; try { metrics = new Metrics(this); } catch (IOException ioe) { getLogger().warning("Unable to create Metrics"); } if (metrics != null) { metrics.start(); pdcm = new PlayerDataCustomMetrics(this, metrics); } PluginManager pm = this.getServer().getPluginManager(); setupVault(pm); playerDataHandler = new PDataHandler(this); PluginCommand playerdata = getCommand("playerdata:playerdata"); if (playerdata != null) { playerdata.setExecutor(new PlayerDataCommandExecutor(this)); } else { getLogger().log(Level.WARNING, "Command /playerdata:playerdata not found! Is another plugin using it?"); } PluginCommand getusername = getCommand("playerdata:getusername"); if (getusername != null) { getusername.setExecutor(new PossibleUserNames(this)); } else { getLogger().log(Level.WARNING, "Command /playerdata:getusername not found! Is another plugin using it?"); } eventListener = new PlayerDataEventListener(this); pm.registerEvents(eventListener, this); handler = new PlayerDataHandler(this); playerDataHandler.init(); if (pdcm != null) { pdcm.addCustom(); } getLogger().info("PlayerData Load Completed"); } /** * */ @Override public void onDisable() { playerDataHandler.endServer(); playerDataHandler.saveAllData(false, null); currentInstance = null; permissionHandler = null; isVaultLoaded = false; getLogger().info("PlayerData Unload Completed"); } /** * This is the internal PDataHandler. Use getHandler() instead if you are * outside of the PlayerData project. * * @return */ public PDataHandler getPDataHandler() { return playerDataHandler; } /** * * @return */ public static PlayerData getCurrentInstance() { return currentInstance; } public PlayerDataHandler getHandler() { return handler; } /** * Get a visually nice date from a timestamp. Acts like: 4 years, 2 months, * 1 day, 10 hours, 30 minutes, and 9 seconds (That is just a random string * of numbers I came up with, but that is what the formating is like) Will * emit any terms that are 0, eg, if 0 days, then it would be 4 years, 2 * months, 10 hours, 30 minutes, and 9 seconds Will put a , between all * terms and also a , and between the last term and the second to last term. * would do 4 years, 2 months and 10 hours returns now if * * @param millis the millisecond value to turn into a date string * @return A visually nice date. "Not That Long" if millis == 0; */ public static String getFormattedDate(long millis) { if (millis == 0) { return "Not That Long"; } long years; long days; long hours; long minutes; long seconds; years = 0; days = TimeUnit.MILLISECONDS.toDays(millis); hours = TimeUnit.MILLISECONDS.toHours(millis) - TimeUnit.DAYS.toHours(days); minutes = TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(hours) - TimeUnit.DAYS.toMinutes(days); seconds = TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(minutes) - TimeUnit.HOURS.toSeconds(hours) - TimeUnit.DAYS.toSeconds(days); - while (days > 365) { - years += 1; - days -= 365; - } + days = days % 365; + years = days / 365; StringBuilder resultBuilder = new StringBuilder(); if (years > 0) { resultBuilder.append(years).append(years == 1 ? " year" : " years"); if (days > 0) { resultBuilder.append(", and "); } } if (days > 0) { - resultBuilder.append(years).append(days == 1 ? " day" : " days"); + resultBuilder.append(days).append(days == 1 ? " day" : " days"); if (hours > 0) { resultBuilder.append(", and "); } } if (hours > 0 && years <= 0) { resultBuilder.append(hours).append(hours == 1 ? " hour" : " hours"); if (minutes > 0 && days <= 0) { resultBuilder.append(", and "); } } if (minutes > 0 && days <= 0 && years <= 0) { resultBuilder.append(minutes).append(minutes == 1 ? " minute" : " minutes"); if (seconds > 0 && hours <= 0) { resultBuilder.append(", and "); } } if (seconds > 0 && hours <= 0 && days <= 0 && years <= 0) { resultBuilder.append(seconds).append(seconds == 1 ? " second" : " seconds"); } return resultBuilder.toString(); } public static String formatList(String[] str) { String returnS = ""; for (int i = 0; i < str.length; i++) { if (!returnS.equals("")) { returnS += ", "; } returnS += str[i]; } return returnS; } public static String getCombinedString(String[] array, int start) { if (array == null || start >= array.length || start < 0) { throw new IllegalArgumentException(); } else if (start + 1 == array.length) { return array[start]; } else { StringBuilder sb = new StringBuilder(array[start]); for (int i = start + 1; i < array.length; i++) { sb.append(" ").append(array[i]); } return sb.toString(); } } private void setupVault(PluginManager pm) { isVaultLoaded = pm.isPluginEnabled("Vault"); if (isVaultLoaded) { RegisteredServiceProvider<Permission> rsp = Bukkit.getServer().getServicesManager().getRegistration(Permission.class); permissionHandler = rsp.getProvider(); if (permissionHandler == null) { isVaultLoaded = false; getLogger().log(Level.INFO, "Vault found, but Permission handler not found."); } else { getLogger().log(Level.INFO, "Vault and Permission handler found."); } } else { getLogger().log(Level.INFO, "Vault not found."); } } public static boolean isVaultLoaded() { return isVaultLoaded; } public static Permission getPermissionHandler() { return permissionHandler; } public PlayerDataEventListener getEventListener() { return eventListener; } }
false
true
public static String getFormattedDate(long millis) { if (millis == 0) { return "Not That Long"; } long years; long days; long hours; long minutes; long seconds; years = 0; days = TimeUnit.MILLISECONDS.toDays(millis); hours = TimeUnit.MILLISECONDS.toHours(millis) - TimeUnit.DAYS.toHours(days); minutes = TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(hours) - TimeUnit.DAYS.toMinutes(days); seconds = TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(minutes) - TimeUnit.HOURS.toSeconds(hours) - TimeUnit.DAYS.toSeconds(days); while (days > 365) { years += 1; days -= 365; } StringBuilder resultBuilder = new StringBuilder(); if (years > 0) { resultBuilder.append(years).append(years == 1 ? " year" : " years"); if (days > 0) { resultBuilder.append(", and "); } } if (days > 0) { resultBuilder.append(years).append(days == 1 ? " day" : " days"); if (hours > 0) { resultBuilder.append(", and "); } } if (hours > 0 && years <= 0) { resultBuilder.append(hours).append(hours == 1 ? " hour" : " hours"); if (minutes > 0 && days <= 0) { resultBuilder.append(", and "); } } if (minutes > 0 && days <= 0 && years <= 0) { resultBuilder.append(minutes).append(minutes == 1 ? " minute" : " minutes"); if (seconds > 0 && hours <= 0) { resultBuilder.append(", and "); } } if (seconds > 0 && hours <= 0 && days <= 0 && years <= 0) { resultBuilder.append(seconds).append(seconds == 1 ? " second" : " seconds"); } return resultBuilder.toString(); }
public static String getFormattedDate(long millis) { if (millis == 0) { return "Not That Long"; } long years; long days; long hours; long minutes; long seconds; years = 0; days = TimeUnit.MILLISECONDS.toDays(millis); hours = TimeUnit.MILLISECONDS.toHours(millis) - TimeUnit.DAYS.toHours(days); minutes = TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(hours) - TimeUnit.DAYS.toMinutes(days); seconds = TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(minutes) - TimeUnit.HOURS.toSeconds(hours) - TimeUnit.DAYS.toSeconds(days); days = days % 365; years = days / 365; StringBuilder resultBuilder = new StringBuilder(); if (years > 0) { resultBuilder.append(years).append(years == 1 ? " year" : " years"); if (days > 0) { resultBuilder.append(", and "); } } if (days > 0) { resultBuilder.append(days).append(days == 1 ? " day" : " days"); if (hours > 0) { resultBuilder.append(", and "); } } if (hours > 0 && years <= 0) { resultBuilder.append(hours).append(hours == 1 ? " hour" : " hours"); if (minutes > 0 && days <= 0) { resultBuilder.append(", and "); } } if (minutes > 0 && days <= 0 && years <= 0) { resultBuilder.append(minutes).append(minutes == 1 ? " minute" : " minutes"); if (seconds > 0 && hours <= 0) { resultBuilder.append(", and "); } } if (seconds > 0 && hours <= 0 && days <= 0 && years <= 0) { resultBuilder.append(seconds).append(seconds == 1 ? " second" : " seconds"); } return resultBuilder.toString(); }
diff --git a/src/main/java/de/l3s/boilerpipe/sax/MediaExtractor.java b/src/main/java/de/l3s/boilerpipe/sax/MediaExtractor.java index e6f1943..d824bc7 100644 --- a/src/main/java/de/l3s/boilerpipe/sax/MediaExtractor.java +++ b/src/main/java/de/l3s/boilerpipe/sax/MediaExtractor.java @@ -1,367 +1,369 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package de.l3s.boilerpipe.sax; import java.io.IOException; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.xerces.parsers.AbstractSAXParser; import org.cyberneko.html.HTMLConfiguration; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import de.l3s.boilerpipe.BoilerpipeExtractor; import de.l3s.boilerpipe.BoilerpipeProcessingException; import de.l3s.boilerpipe.document.Image; import de.l3s.boilerpipe.document.Media; import de.l3s.boilerpipe.document.TextBlock; import de.l3s.boilerpipe.document.TextDocument; import de.l3s.boilerpipe.document.VimeoVideo; import de.l3s.boilerpipe.document.YoutubeVideo; import de.l3s.boilerpipe.sax.BoilerpipeSAXInput; import de.l3s.boilerpipe.sax.HTMLDocument; import de.l3s.boilerpipe.sax.HTMLFetcher; /** * Extracts youtube and vimeo videos that are enclosed by extracted content. * * @author Christian Kohlschütter, [email protected] */ public final class MediaExtractor { /** */ public static final MediaExtractor INSTANCE = new MediaExtractor(); /** * @return the singleton instance of {@link MediaExtractor}. */ public static MediaExtractor getInstance() { return INSTANCE; } /** * Processes the given {@link TextDocument} and the original HTML text (as a * String). * * @param doc * The processed {@link TextDocument}. * @param origHTML * The original HTML document. * @return A List of enclosed {@link Image}s * @throws BoilerpipeProcessingException if an error during extraction occure */ public List<Media> process(final TextDocument doc, final String origHTML) throws BoilerpipeProcessingException { return process(doc, new InputSource(new StringReader(origHTML))); } /** * Processes the given {@link TextDocument} and the original HTML text (as an * {@link InputSource}). * * @param doc * The processed {@link TextDocument}. * The original HTML document. * @return A List of enclosed {@link Image}s * @throws BoilerpipeProcessingException */ public List<Media> process(final TextDocument doc, final InputSource is) throws BoilerpipeProcessingException { final Implementation implementation = new Implementation(); implementation.process(doc, is); return implementation.linksHighlight; } /** * Fetches the given {@link URL} using {@link HTMLFetcher} and processes the * retrieved HTML using the specified {@link BoilerpipeExtractor}. * @param url the url of the document to fetch * @param extractor extractor to use * * @return A List of enclosed {@link Image}s * @throws IOException * @throws BoilerpipeProcessingException * @throws SAXException */ @SuppressWarnings("javadoc") public List<Media> process(final URL url, final BoilerpipeExtractor extractor) throws IOException, BoilerpipeProcessingException, SAXException { final HTMLDocument htmlDoc = HTMLFetcher.fetch(url); final TextDocument doc = new BoilerpipeSAXInput(htmlDoc.toInputSource()) .getTextDocument(); extractor.process(doc); final InputSource is = htmlDoc.toInputSource(); return process(doc, is); } /** * parses the media (picture, video) out of doc * @param doc document to parse the media out * @param extractor extractor to use * @return list of extracted media, with size = 0 if no media found */ public List<Media> process(String doc, final BoilerpipeExtractor extractor) { final HTMLDocument htmlDoc = new HTMLDocument(doc); List<Media> media = new ArrayList<Media>(); TextDocument tdoc; try { tdoc = new BoilerpipeSAXInput(htmlDoc.toInputSource()).getTextDocument(); extractor.process(tdoc); final InputSource is = htmlDoc.toInputSource(); media = process(tdoc, is); } catch (Exception e) { return null; } return media; } private final class Implementation extends AbstractSAXParser implements ContentHandler { List<Media> linksHighlight = new ArrayList<Media>(); private List<Media> linksBuffer = new ArrayList<Media>(); private int inIgnorableElement = 0; private int characterElementIdx = 0; private final BitSet contentBitSet = new BitSet(); private boolean inHighlight = false; Implementation() { super(new HTMLConfiguration()); setContentHandler(this); } void process(final TextDocument doc, final InputSource is) throws BoilerpipeProcessingException { for (TextBlock block : doc.getTextBlocks()) { if (block.isContent()) { final BitSet bs = block.getContainedTextElements(); if (bs != null) { contentBitSet.or(bs); } } } try { parse(is); } catch (SAXException e) { throw new BoilerpipeProcessingException(e); } catch (IOException e) { throw new BoilerpipeProcessingException(e); } } public void endDocument() throws SAXException { } public void endPrefixMapping(String prefix) throws SAXException { } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { } public void processingInstruction(String target, String data) throws SAXException { } public void setDocumentLocator(Locator locator) { } public void skippedEntity(String name) throws SAXException { } public void startDocument() throws SAXException { } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { TagAction ta = TAG_ACTIONS.get(localName); if (ta != null) { ta.beforeStart(this, localName); } try { if (inIgnorableElement == 0) { if(inHighlight && "IFRAME".equalsIgnoreCase(localName)) { String src = atts.getValue("src"); - src = src.replaceAll("\\\\\"", ""); + if (src != null) { + src = src.replaceAll("\\\\\"", ""); + } if(src != null && src.length() > 0 && src.contains("youtube.com/embed/")) { String originUrl = null; try { URL url = new URL(src); String path = url.getPath(); String[] pathParts = path.split("/"); originUrl = "http://www.youtube.com/watch?v="+pathParts[pathParts.length-1]; linksBuffer.add(new YoutubeVideo(originUrl,src)); } catch (MalformedURLException e) { } } if(src != null && src.length() > 0 && src.contains("player.vimeo.com")) { String originUrl = null; try { URL url = new URL(src); String path = url.getPath(); String[] pathParts = path.split("/"); originUrl = "http://vimeo.com/"+pathParts[pathParts.length-1]; linksBuffer.add(new VimeoVideo(originUrl,src)); } catch (MalformedURLException e) { } } } if(inHighlight && "IMG".equalsIgnoreCase(localName)) { String src = atts.getValue("src"); try { URI image = new URI(src); if(src != null && src.length() > 0) { linksBuffer.add(new Image(src, atts.getValue("width"), atts.getValue("height"), atts.getValue("alt"))); } } catch (URISyntaxException e) { } } } } finally { if (ta != null) { ta.afterStart(this, localName); } } } public void endElement(String uri, String localName, String qName) throws SAXException { TagAction ta = TAG_ACTIONS.get(localName); if (ta != null) { ta.beforeEnd(this, localName); } try { if (inIgnorableElement == 0) { // } } finally { if (ta != null) { ta.afterEnd(this, localName); } } } public void characters(char[] ch, int start, int length) throws SAXException { characterElementIdx++; if (inIgnorableElement == 0) { boolean highlight = contentBitSet.get(characterElementIdx); if(!highlight) { if(length == 0) { return; } boolean justWhitespace = true; for(int i=start;i<start+length;i++) { if(!Character.isWhitespace(ch[i])) { justWhitespace = false; break; } } if(justWhitespace) { return; } } inHighlight = highlight; if(inHighlight) { linksHighlight.addAll(linksBuffer); linksBuffer.clear(); } } } public void startPrefixMapping(String prefix, String uri) throws SAXException { } } @SuppressWarnings("synthetic-access") private static final TagAction TA_IGNORABLE_ELEMENT = new TagAction() { @Override void beforeStart(final Implementation instance, final String localName) { instance.inIgnorableElement++; } @Override void afterEnd(final Implementation instance, final String localName) { instance.inIgnorableElement--; } }; private static Map<String, TagAction> TAG_ACTIONS = new HashMap<String, TagAction>(); static { TAG_ACTIONS.put("STYLE", TA_IGNORABLE_ELEMENT); TAG_ACTIONS.put("SCRIPT", TA_IGNORABLE_ELEMENT); TAG_ACTIONS.put("OPTION", TA_IGNORABLE_ELEMENT); TAG_ACTIONS.put("NOSCRIPT", TA_IGNORABLE_ELEMENT); TAG_ACTIONS.put("EMBED", TA_IGNORABLE_ELEMENT); TAG_ACTIONS.put("APPLET", TA_IGNORABLE_ELEMENT); TAG_ACTIONS.put("LINK", TA_IGNORABLE_ELEMENT); TAG_ACTIONS.put("HEAD", TA_IGNORABLE_ELEMENT); } private abstract static class TagAction { void beforeStart(final Implementation instance, final String localName) { } void afterStart(final Implementation instance, final String localName) { } void beforeEnd(final Implementation instance, final String localName) { } void afterEnd(final Implementation instance, final String localName) { } } }
true
true
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { TagAction ta = TAG_ACTIONS.get(localName); if (ta != null) { ta.beforeStart(this, localName); } try { if (inIgnorableElement == 0) { if(inHighlight && "IFRAME".equalsIgnoreCase(localName)) { String src = atts.getValue("src"); src = src.replaceAll("\\\\\"", ""); if(src != null && src.length() > 0 && src.contains("youtube.com/embed/")) { String originUrl = null; try { URL url = new URL(src); String path = url.getPath(); String[] pathParts = path.split("/"); originUrl = "http://www.youtube.com/watch?v="+pathParts[pathParts.length-1]; linksBuffer.add(new YoutubeVideo(originUrl,src)); } catch (MalformedURLException e) { } } if(src != null && src.length() > 0 && src.contains("player.vimeo.com")) { String originUrl = null; try { URL url = new URL(src); String path = url.getPath(); String[] pathParts = path.split("/"); originUrl = "http://vimeo.com/"+pathParts[pathParts.length-1]; linksBuffer.add(new VimeoVideo(originUrl,src)); } catch (MalformedURLException e) { } } } if(inHighlight && "IMG".equalsIgnoreCase(localName)) { String src = atts.getValue("src"); try { URI image = new URI(src); if(src != null && src.length() > 0) { linksBuffer.add(new Image(src, atts.getValue("width"), atts.getValue("height"), atts.getValue("alt"))); } } catch (URISyntaxException e) { } } } } finally { if (ta != null) { ta.afterStart(this, localName); } } }
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { TagAction ta = TAG_ACTIONS.get(localName); if (ta != null) { ta.beforeStart(this, localName); } try { if (inIgnorableElement == 0) { if(inHighlight && "IFRAME".equalsIgnoreCase(localName)) { String src = atts.getValue("src"); if (src != null) { src = src.replaceAll("\\\\\"", ""); } if(src != null && src.length() > 0 && src.contains("youtube.com/embed/")) { String originUrl = null; try { URL url = new URL(src); String path = url.getPath(); String[] pathParts = path.split("/"); originUrl = "http://www.youtube.com/watch?v="+pathParts[pathParts.length-1]; linksBuffer.add(new YoutubeVideo(originUrl,src)); } catch (MalformedURLException e) { } } if(src != null && src.length() > 0 && src.contains("player.vimeo.com")) { String originUrl = null; try { URL url = new URL(src); String path = url.getPath(); String[] pathParts = path.split("/"); originUrl = "http://vimeo.com/"+pathParts[pathParts.length-1]; linksBuffer.add(new VimeoVideo(originUrl,src)); } catch (MalformedURLException e) { } } } if(inHighlight && "IMG".equalsIgnoreCase(localName)) { String src = atts.getValue("src"); try { URI image = new URI(src); if(src != null && src.length() > 0) { linksBuffer.add(new Image(src, atts.getValue("width"), atts.getValue("height"), atts.getValue("alt"))); } } catch (URISyntaxException e) { } } } } finally { if (ta != null) { ta.afterStart(this, localName); } } }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/OpenTaskAction.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/OpenTaskAction.java index 8bada682b..8b8975326 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/OpenTaskAction.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/OpenTaskAction.java @@ -1,59 +1,59 @@ /******************************************************************************* * Copyright (c) 2004, 2008 Willian Mitsuda and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Willian Mitsuda - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.internal.tasks.ui.actions; import org.eclipse.jface.action.IAction; import org.eclipse.jface.window.Window; import org.eclipse.mylyn.internal.tasks.core.AbstractTask; import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal; import org.eclipse.mylyn.tasks.core.ITask; import org.eclipse.mylyn.tasks.ui.TasksUiUtil; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkbenchWindowActionDelegate; import org.eclipse.ui.actions.ActionDelegate; /** * @author Willian Mitsuda */ public class OpenTaskAction extends ActionDelegate implements IWorkbenchWindowActionDelegate { private IWorkbenchWindow window; public void init(IWorkbenchWindow window) { this.window = window; } @Override public void run(IAction action) { - TaskSelectionDialogWithRandom dlg = new TaskSelectionDialogWithRandom(window.getShell()); + TaskSelectionDialog dlg = new TaskSelectionDialog(window.getShell()); dlg.setTitle(Messages.OpenTaskAction_Open_Task); dlg.setMessage(Messages.OpenTaskAction_Select_a_task_to_open__); dlg.setShowExtendedOpeningOptions(true); if (dlg.open() != Window.OK) { return; } Object result = dlg.getFirstResult(); if (result instanceof ITask) { AbstractTask task = (AbstractTask) result; if (dlg.getOpenInBrowser()) { if (TasksUiInternal.isValidUrl(task.getUrl())) { TasksUiUtil.openUrl(task.getUrl()); } } else { TasksUiInternal.refreshAndOpenTaskListElement(task); } } } }
true
true
public void run(IAction action) { TaskSelectionDialogWithRandom dlg = new TaskSelectionDialogWithRandom(window.getShell()); dlg.setTitle(Messages.OpenTaskAction_Open_Task); dlg.setMessage(Messages.OpenTaskAction_Select_a_task_to_open__); dlg.setShowExtendedOpeningOptions(true); if (dlg.open() != Window.OK) { return; } Object result = dlg.getFirstResult(); if (result instanceof ITask) { AbstractTask task = (AbstractTask) result; if (dlg.getOpenInBrowser()) { if (TasksUiInternal.isValidUrl(task.getUrl())) { TasksUiUtil.openUrl(task.getUrl()); } } else { TasksUiInternal.refreshAndOpenTaskListElement(task); } } }
public void run(IAction action) { TaskSelectionDialog dlg = new TaskSelectionDialog(window.getShell()); dlg.setTitle(Messages.OpenTaskAction_Open_Task); dlg.setMessage(Messages.OpenTaskAction_Select_a_task_to_open__); dlg.setShowExtendedOpeningOptions(true); if (dlg.open() != Window.OK) { return; } Object result = dlg.getFirstResult(); if (result instanceof ITask) { AbstractTask task = (AbstractTask) result; if (dlg.getOpenInBrowser()) { if (TasksUiInternal.isValidUrl(task.getUrl())) { TasksUiUtil.openUrl(task.getUrl()); } } else { TasksUiInternal.refreshAndOpenTaskListElement(task); } } }
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/Main.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/Main.java index 52f21ac8..7515b03d 100644 --- a/src/checkstyle/com/puppycrawl/tools/checkstyle/Main.java +++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/Main.java @@ -1,316 +1,317 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2005 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.List; import java.util.Properties; import java.util.LinkedList; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import com.puppycrawl.tools.checkstyle.api.AuditListener; import com.puppycrawl.tools.checkstyle.api.Configuration; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; /** * Wrapper command line program for the Checker. * @author Oliver Burn **/ public final class Main { /** the options to the command line */ private static final Options OPTS = new Options(); static { OPTS.addOption("c", true, "The check configuration file to use."); OPTS.addOption("r", true, "Traverse the directory for source files"); OPTS.addOption("o", true, "Sets the output file. Defaults to stdout"); OPTS.addOption("p", true, "Loads the properties file"); OPTS.addOption("n", true, "Loads the package names file"); OPTS.addOption( "f", true, "Sets the output format. (plain|xml). Defaults to plain"); } /** * Loops over the files specified checking them for errors. The exit code * is the number of errors found in all the files. * @param aArgs the command line arguments **/ public static void main(String[] aArgs) { // parse the parameters final CommandLineParser clp = new PosixParser(); CommandLine line = null; try { line = clp.parse(OPTS, aArgs); } catch (final ParseException e) { e.printStackTrace(); usage(); } + assert line != null; // setup the properties final Properties props = line.hasOption("p") ? loadProperties(new File(line.getOptionValue("p"))) : System.getProperties(); // ensure a config file is specified if (!line.hasOption("c")) { System.out.println("Must specify a config XML file."); usage(); } final Configuration config = loadConfig(line, props); //Load the set of package names ModuleFactory moduleFactory = null; if (line.hasOption("n")) { moduleFactory = loadPackages(line); } // setup the output stream OutputStream out = null; boolean closeOut = false; if (line.hasOption("o")) { final String fname = line.getOptionValue("o"); try { out = new FileOutputStream(fname); closeOut = true; } catch (final FileNotFoundException e) { System.out.println("Could not find file: '" + fname + "'"); System.exit(1); } } else { out = System.out; closeOut = false; } final AuditListener listener = createListener(line, out, closeOut); final List files = getFilesToProcess(line); final Checker c = createChecker(config, moduleFactory, listener); final File[] processedFiles = new File[files.size()]; files.toArray(processedFiles); final int numErrs = c.process(processedFiles); c.destroy(); System.exit(numErrs); } /** * Creates the Checker object. * * @param aConfig the configuration to use * @param aFactory the module factor to use * @param aNosy the sticky beak to track what happens * @return a nice new fresh Checker */ private static Checker createChecker(Configuration aConfig, ModuleFactory aFactory, AuditListener aNosy) { Checker c = null; try { c = new Checker(); c.setModuleFactory(aFactory); c.configure(aConfig); c.addListener(aNosy); } catch (final Exception e) { System.out.println("Unable to create Checker: " + e.getMessage()); e.printStackTrace(System.out); System.exit(1); } return c; } /** * Determines the files to process. * * @param aLine the command line options specifying what files to process * @return list of files to process */ private static List getFilesToProcess(CommandLine aLine) { final List files = new LinkedList(); if (aLine.hasOption("r")) { final String[] values = aLine.getOptionValues("r"); for (int i = 0; i < values.length; i++) { traverse(new File(values[i]), files); } } final String[] remainingArgs = aLine.getArgs(); for (int i = 0; i < remainingArgs.length; i++) { files.add(new File(remainingArgs[i])); } if (files.isEmpty()) { System.out.println("Must specify files to process"); usage(); } return files; } /** * Create the audit listener * * @param aLine command line options supplied * @param aOut the stream to log to * @param aCloseOut whether the stream should be closed * @return a fresh new <code>AuditListener</code> */ private static AuditListener createListener(CommandLine aLine, OutputStream aOut, boolean aCloseOut) { final String format = aLine.hasOption("f") ? aLine.getOptionValue("f") : "plain"; AuditListener listener = null; if ("xml".equals(format)) { listener = new XMLLogger(aOut, aCloseOut); } else if ("plain".equals(format)) { listener = new DefaultLogger(aOut, aCloseOut); } else { System.out.println("Invalid format: (" + format + "). Must be 'plain' or 'xml'."); usage(); } return listener; } /** * Loads the packages, or exists if unable to. * * @param aLine the supplied command line options * @return a fresh new <code>ModuleFactory</code> */ private static ModuleFactory loadPackages(CommandLine aLine) { try { return PackageNamesLoader.loadModuleFactory( aLine.getOptionValue("n")); } catch (final CheckstyleException e) { System.out.println("Error loading package names file"); e.printStackTrace(System.out); System.exit(1); return null; // never get here } } /** * Loads the configuration file. Will exit if unable to load. * * @param aLine specifies the location of the configuration * @param aProps the properties to resolve with the configuration * @return a fresh new configuration */ private static Configuration loadConfig(CommandLine aLine, Properties aProps) { try { return ConfigurationLoader.loadConfiguration( aLine.getOptionValue("c"), new PropertiesExpander(aProps)); } catch (final CheckstyleException e) { System.out.println("Error loading configuration file"); e.printStackTrace(System.out); System.exit(1); return null; // can never get here } } /** Prints the usage information. **/ private static void usage() { final HelpFormatter hf = new HelpFormatter(); hf.printHelp( "java " + Main.class.getName() + " [options] -c <config.xml> file...", OPTS); System.exit(1); } /** * Traverses a specified node looking for files to check. Found * files are added to a specified list. Subdirectories are also * traversed. * * @param aNode the node to process * @param aFiles list to add found files to */ private static void traverse(File aNode, List aFiles) { if (aNode.canRead()) { if (aNode.isDirectory()) { final File[] nodes = aNode.listFiles(); for (int i = 0; i < nodes.length; i++) { traverse(nodes[i], aFiles); } } else if (aNode.isFile()) { aFiles.add(aNode); } } } /** * Loads properties from a File. * @param aFile the properties file * @return the properties in aFile */ private static Properties loadProperties(File aFile) { final Properties properties = new Properties(); try { FileInputStream fis = null; fis = new FileInputStream(aFile); properties.load(fis); fis.close(); } catch (final IOException ex) { System.out.println("Unable to load properties from file: " + aFile.getAbsolutePath()); ex.printStackTrace(System.out); System.exit(1); } return properties; } }
true
true
public static void main(String[] aArgs) { // parse the parameters final CommandLineParser clp = new PosixParser(); CommandLine line = null; try { line = clp.parse(OPTS, aArgs); } catch (final ParseException e) { e.printStackTrace(); usage(); } // setup the properties final Properties props = line.hasOption("p") ? loadProperties(new File(line.getOptionValue("p"))) : System.getProperties(); // ensure a config file is specified if (!line.hasOption("c")) { System.out.println("Must specify a config XML file."); usage(); } final Configuration config = loadConfig(line, props); //Load the set of package names ModuleFactory moduleFactory = null; if (line.hasOption("n")) { moduleFactory = loadPackages(line); } // setup the output stream OutputStream out = null; boolean closeOut = false; if (line.hasOption("o")) { final String fname = line.getOptionValue("o"); try { out = new FileOutputStream(fname); closeOut = true; } catch (final FileNotFoundException e) { System.out.println("Could not find file: '" + fname + "'"); System.exit(1); } } else { out = System.out; closeOut = false; } final AuditListener listener = createListener(line, out, closeOut); final List files = getFilesToProcess(line); final Checker c = createChecker(config, moduleFactory, listener); final File[] processedFiles = new File[files.size()]; files.toArray(processedFiles); final int numErrs = c.process(processedFiles); c.destroy(); System.exit(numErrs); }
public static void main(String[] aArgs) { // parse the parameters final CommandLineParser clp = new PosixParser(); CommandLine line = null; try { line = clp.parse(OPTS, aArgs); } catch (final ParseException e) { e.printStackTrace(); usage(); } assert line != null; // setup the properties final Properties props = line.hasOption("p") ? loadProperties(new File(line.getOptionValue("p"))) : System.getProperties(); // ensure a config file is specified if (!line.hasOption("c")) { System.out.println("Must specify a config XML file."); usage(); } final Configuration config = loadConfig(line, props); //Load the set of package names ModuleFactory moduleFactory = null; if (line.hasOption("n")) { moduleFactory = loadPackages(line); } // setup the output stream OutputStream out = null; boolean closeOut = false; if (line.hasOption("o")) { final String fname = line.getOptionValue("o"); try { out = new FileOutputStream(fname); closeOut = true; } catch (final FileNotFoundException e) { System.out.println("Could not find file: '" + fname + "'"); System.exit(1); } } else { out = System.out; closeOut = false; } final AuditListener listener = createListener(line, out, closeOut); final List files = getFilesToProcess(line); final Checker c = createChecker(config, moduleFactory, listener); final File[] processedFiles = new File[files.size()]; files.toArray(processedFiles); final int numErrs = c.process(processedFiles); c.destroy(); System.exit(numErrs); }
diff --git a/examples/quickstart/src/test/functional/org/springside/examples/quickstart/functional/rest/TaskRestIT.java b/examples/quickstart/src/test/functional/org/springside/examples/quickstart/functional/rest/TaskRestIT.java index 77a4de3..021275d 100644 --- a/examples/quickstart/src/test/functional/org/springside/examples/quickstart/functional/rest/TaskRestIT.java +++ b/examples/quickstart/src/test/functional/org/springside/examples/quickstart/functional/rest/TaskRestIT.java @@ -1,90 +1,90 @@ package org.springside.examples.quickstart.functional.rest; import static org.junit.Assert.*; import java.net.URI; import java.util.ArrayList; import org.apache.commons.lang3.StringUtils; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import org.springframework.web.client.RestTemplate; import org.springside.examples.quickstart.data.TaskData; import org.springside.examples.quickstart.entity.Task; import org.springside.examples.quickstart.functional.BaseFunctionalTestCase; import org.springside.modules.test.category.Smoke; /** * 任务管理的功能测试, 测试页面JavaScript及主要用户故事流程. * * @author calvin */ public class TaskRestIT extends BaseFunctionalTestCase { private final RestTemplate restTemplate = new RestTemplate(); private static class TaskList extends ArrayList<Task> { }; private static String resoureUrl; @BeforeClass public static void initUrl() { resoureUrl = baseUrl + "/api/task"; } /** * 查看任务列表. */ @Test @Category(Smoke.class) public void listTasks() { TaskList tasks = restTemplate.getForObject(resoureUrl, TaskList.class); assertEquals(5, tasks.size()); assertEquals("Study PlayFramework 2.0", tasks.get(0).getTitle()); } /** * 获取任务. */ @Test @Category(Smoke.class) public void getTask() { Long id = 1L; Task task = restTemplate.getForObject(resoureUrl + "/{id}", Task.class, id); assertEquals("Study PlayFramework 2.0", task.getTitle()); } /** * 创建/更新/删除任务. */ @Test @Category(Smoke.class) public void createUpdateAndDeleteTask() { //create Task task = TaskData.randomTask(); URI taskUri = restTemplate.postForLocation(resoureUrl, task); - assertEquals(resoureUrl + "/6", taskUri.toString()); + Task createdTask = restTemplate.getForObject(taskUri, Task.class); + assertEquals(task.getTitle(), createdTask.getTitle()); //update String id = StringUtils.substringAfterLast(taskUri.toString(), "/"); - String newTitle = TaskData.randomTitle(); task.setId(new Long(id)); - task.setTitle(newTitle); + task.setTitle(TaskData.randomTitle()); restTemplate.put(taskUri, task); Task updatedTask = restTemplate.getForObject(taskUri, Task.class); - assertEquals(newTitle, updatedTask.getTitle()); + assertEquals(task.getTitle(), updatedTask.getTitle()); //delete restTemplate.delete(taskUri); Task deletedTask = restTemplate.getForObject(taskUri, Task.class); assertNull(deletedTask); } }
false
true
public void createUpdateAndDeleteTask() { //create Task task = TaskData.randomTask(); URI taskUri = restTemplate.postForLocation(resoureUrl, task); assertEquals(resoureUrl + "/6", taskUri.toString()); //update String id = StringUtils.substringAfterLast(taskUri.toString(), "/"); String newTitle = TaskData.randomTitle(); task.setId(new Long(id)); task.setTitle(newTitle); restTemplate.put(taskUri, task); Task updatedTask = restTemplate.getForObject(taskUri, Task.class); assertEquals(newTitle, updatedTask.getTitle()); //delete restTemplate.delete(taskUri); Task deletedTask = restTemplate.getForObject(taskUri, Task.class); assertNull(deletedTask); }
public void createUpdateAndDeleteTask() { //create Task task = TaskData.randomTask(); URI taskUri = restTemplate.postForLocation(resoureUrl, task); Task createdTask = restTemplate.getForObject(taskUri, Task.class); assertEquals(task.getTitle(), createdTask.getTitle()); //update String id = StringUtils.substringAfterLast(taskUri.toString(), "/"); task.setId(new Long(id)); task.setTitle(TaskData.randomTitle()); restTemplate.put(taskUri, task); Task updatedTask = restTemplate.getForObject(taskUri, Task.class); assertEquals(task.getTitle(), updatedTask.getTitle()); //delete restTemplate.delete(taskUri); Task deletedTask = restTemplate.getForObject(taskUri, Task.class); assertNull(deletedTask); }
diff --git a/src/main/java/net/yeputons/cscenter/dbfall2013/engines/HashTrieEngine.java b/src/main/java/net/yeputons/cscenter/dbfall2013/engines/HashTrieEngine.java index d68c1bd..232094c 100644 --- a/src/main/java/net/yeputons/cscenter/dbfall2013/engines/HashTrieEngine.java +++ b/src/main/java/net/yeputons/cscenter/dbfall2013/engines/HashTrieEngine.java @@ -1,223 +1,229 @@ package net.yeputons.cscenter.dbfall2013.engines; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashSet; import java.util.NoSuchElementException; import java.util.Set; /** * Created with IntelliJ IDEA. * User: e.suvorov * Date: 05.10.13 * Time: 20:59 * To change this template use File | Settings | File Templates. */ public class HashTrieEngine extends SimpleEngine { protected File storage; protected RandomAccessFile data; protected final static MessageDigest md; protected final int MD_LEN = 160 / 8; protected int currentSize; static { try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } protected void openStorage() throws IOException { data = new RandomAccessFile(storage, "rw"); if (data.length() == 0) { data.writeInt(0); for (int i = 0; i < 256; i++) data.writeInt(0); } currentSize = keySet().size(); } public HashTrieEngine(File storage) throws IOException { this.storage = storage; openStorage(); } public void flush() throws IOException { data.getFD().sync(); } public void close() throws IOException { data.close(); } @Override public void clear() { try { close(); storage.delete(); openStorage(); } catch (IOException e) { throw new RuntimeException(e); } } private void keySet(int ptr, int depth, Set<ByteBuffer> keySet) throws IOException { data.seek(ptr); if (depth == MD_LEN) { int valLen = data.readInt(); if (valLen == -1) return; data.skipBytes(valLen); int keyLen = data.readInt(); byte[] key = new byte[keyLen]; data.read(key); keySet.add(ByteBuffer.wrap(key)); return; } int[] ptrs = new int[256]; for (int i = 0; i < ptrs.length; i++) { ptrs[i] = data.readInt(); } for (int i = 0; i < ptrs.length; i++) if (ptrs[i] != 0) keySet(ptrs[i], depth + 1, keySet); } @Override public Set<ByteBuffer> keySet() { Set<ByteBuffer> keySet = new HashSet<ByteBuffer>(); try { keySet(4, 0, keySet); } catch (IOException e) { throw new RuntimeException(e); } return keySet; } @Override public int size() { return currentSize; } protected int getNode(ByteBuffer key) { int ptr = 4; byte[] hash = md.digest(key.array()); assert hash.length == MD_LEN; try { for (int i = 0; i < hash.length; i++) { int cur = hash[i] & 0xFF; data.seek(ptr + 4 * cur); int nptr = data.readInt(); if (nptr == 0) throw new NoSuchElementException(); ptr = nptr; } data.seek(ptr); if (data.readInt() == -1) throw new NoSuchElementException(); return ptr; } catch (IOException e) { throw new RuntimeException(e); } } @Override public ByteBuffer get(Object _key) { if (size() == 0) return null; ByteBuffer key = (ByteBuffer)_key; try { int ptr = getNode(key); data.seek(ptr); byte[] res = new byte[data.readInt()]; data.read(res); return ByteBuffer.wrap(res); } catch (IOException e) { throw new RuntimeException(e); } catch (NoSuchElementException e) { return null; } } @Override public ByteBuffer put(ByteBuffer key, ByteBuffer value) { if (key == null || value == null) throw new NullPointerException("key and value should not be nulls"); byte[] hash = md.digest(key.array()); assert hash.length == MD_LEN; int ptr = 4; try { for (int i = 0; i < hash.length; i++) { int cur = hash[i] & 0xFF; if (ptr == data.length()) { data.seek(ptr); for (int i2 = 0; i2 < 256; i2++) data.writeInt(0); } data.seek(ptr + 4 * cur); int nptr = data.readInt(); if (i + 1 < hash.length) { if (nptr == 0) { nptr = (int)data.length(); data.seek(ptr + 4 * cur); data.writeInt(nptr); } ptr = nptr; } else { ByteBuffer oldVal = null; - if (nptr < data.length()) { - byte[] buf = new byte[data.readInt()]; - data.read(buf); - oldVal = ByteBuffer.wrap(buf); + if (nptr > 0 && nptr < data.length()) { + data.seek(nptr); + int valueLen = data.readInt(); + if (valueLen != -1) { + byte[] buf = new byte[valueLen]; + data.read(buf); + oldVal = ByteBuffer.wrap(buf); + } } nptr = (int)data.length(); data.seek(ptr + 4 * cur); data.writeInt(nptr); data.seek(nptr); data.writeInt(value.array().length); data.write(value.array()); data.writeInt(key.array().length); data.write(key.array()); - currentSize += 1; - data.seek(0); - data.writeInt(currentSize); + if (oldVal == null) { + currentSize += 1; + data.seek(0); + data.writeInt(currentSize); + } return oldVal; } } throw new AssertionError("Reached end of function"); } catch (IOException e) { throw new RuntimeException(e); } } @Override public ByteBuffer remove(Object _key) { ByteBuffer key = (ByteBuffer)_key; try { int ptr = getNode(key); data.seek(ptr); byte[] old = new byte[data.readInt()]; data.read(old); data.seek(ptr); data.writeInt(-1); currentSize -= 1; data.seek(0); data.writeInt(currentSize); return ByteBuffer.wrap(old); } catch (IOException e){ throw new RuntimeException(e); } catch (NoSuchElementException e) { return null; } } }
false
true
public ByteBuffer put(ByteBuffer key, ByteBuffer value) { if (key == null || value == null) throw new NullPointerException("key and value should not be nulls"); byte[] hash = md.digest(key.array()); assert hash.length == MD_LEN; int ptr = 4; try { for (int i = 0; i < hash.length; i++) { int cur = hash[i] & 0xFF; if (ptr == data.length()) { data.seek(ptr); for (int i2 = 0; i2 < 256; i2++) data.writeInt(0); } data.seek(ptr + 4 * cur); int nptr = data.readInt(); if (i + 1 < hash.length) { if (nptr == 0) { nptr = (int)data.length(); data.seek(ptr + 4 * cur); data.writeInt(nptr); } ptr = nptr; } else { ByteBuffer oldVal = null; if (nptr < data.length()) { byte[] buf = new byte[data.readInt()]; data.read(buf); oldVal = ByteBuffer.wrap(buf); } nptr = (int)data.length(); data.seek(ptr + 4 * cur); data.writeInt(nptr); data.seek(nptr); data.writeInt(value.array().length); data.write(value.array()); data.writeInt(key.array().length); data.write(key.array()); currentSize += 1; data.seek(0); data.writeInt(currentSize); return oldVal; } } throw new AssertionError("Reached end of function"); } catch (IOException e) { throw new RuntimeException(e); } }
public ByteBuffer put(ByteBuffer key, ByteBuffer value) { if (key == null || value == null) throw new NullPointerException("key and value should not be nulls"); byte[] hash = md.digest(key.array()); assert hash.length == MD_LEN; int ptr = 4; try { for (int i = 0; i < hash.length; i++) { int cur = hash[i] & 0xFF; if (ptr == data.length()) { data.seek(ptr); for (int i2 = 0; i2 < 256; i2++) data.writeInt(0); } data.seek(ptr + 4 * cur); int nptr = data.readInt(); if (i + 1 < hash.length) { if (nptr == 0) { nptr = (int)data.length(); data.seek(ptr + 4 * cur); data.writeInt(nptr); } ptr = nptr; } else { ByteBuffer oldVal = null; if (nptr > 0 && nptr < data.length()) { data.seek(nptr); int valueLen = data.readInt(); if (valueLen != -1) { byte[] buf = new byte[valueLen]; data.read(buf); oldVal = ByteBuffer.wrap(buf); } } nptr = (int)data.length(); data.seek(ptr + 4 * cur); data.writeInt(nptr); data.seek(nptr); data.writeInt(value.array().length); data.write(value.array()); data.writeInt(key.array().length); data.write(key.array()); if (oldVal == null) { currentSize += 1; data.seek(0); data.writeInt(currentSize); } return oldVal; } } throw new AssertionError("Reached end of function"); } catch (IOException e) { throw new RuntimeException(e); } }
diff --git a/tools/src/test/java/org/apache/tuscany/sdo/test/AllTests.java b/tools/src/test/java/org/apache/tuscany/sdo/test/AllTests.java index 9873419..c1af67d 100644 --- a/tools/src/test/java/org/apache/tuscany/sdo/test/AllTests.java +++ b/tools/src/test/java/org/apache/tuscany/sdo/test/AllTests.java @@ -1,30 +1,30 @@ package org.apache.tuscany.sdo.test; import junit.framework.TestCase; import junit.framework.TestSuite; public class AllTests extends TestCase { public static TestSuite suite() { TestSuite suite = new TestSuite(); // suite.addTestSuite(ChangeSummaryOnDataObjectTestCase.class); suite.addTestSuite(ChangeSummaryGenTestCase.class); suite.addTestSuite(GenPatternsTestCase.class); - suite.addTestSuite(org.apache.tuscany.sdo.test.StaticSequenceNoEmfTestCase.class); + //suite.addTestSuite(org.apache.tuscany.sdo.test.StaticSequenceNoEmfTestCase.class); return suite; } /** * Runs the test suite using the textual runner. */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } }
true
true
public static TestSuite suite() { TestSuite suite = new TestSuite(); // suite.addTestSuite(ChangeSummaryOnDataObjectTestCase.class); suite.addTestSuite(ChangeSummaryGenTestCase.class); suite.addTestSuite(GenPatternsTestCase.class); suite.addTestSuite(org.apache.tuscany.sdo.test.StaticSequenceNoEmfTestCase.class); return suite; }
public static TestSuite suite() { TestSuite suite = new TestSuite(); // suite.addTestSuite(ChangeSummaryOnDataObjectTestCase.class); suite.addTestSuite(ChangeSummaryGenTestCase.class); suite.addTestSuite(GenPatternsTestCase.class); //suite.addTestSuite(org.apache.tuscany.sdo.test.StaticSequenceNoEmfTestCase.class); return suite; }
diff --git a/tools/host/src/com/android/cts/HostTimer.java b/tools/host/src/com/android/cts/HostTimer.java index 2cd2a290..f2181a9c 100644 --- a/tools/host/src/com/android/cts/HostTimer.java +++ b/tools/host/src/com/android/cts/HostTimer.java @@ -1,159 +1,161 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.cts; import java.util.Timer; import java.util.TimerTask; /** * Host timer. * Generally, there are two use cases of this general host timer: * <ul> * <li> Use it as general timer to guard host from running for * too long under some situations. * <li> Use it as special timer where host needs to run very * long to communicate with device to fetch result section * by section which requires restarting the timer. * </ul> */ public class HostTimer { private final static int INIT = 0; private final static int RUNNING = 1; private final static int CANCELLED = 2; private final static int TIMEOUT = 3; private boolean mIsNotified; private int mStatus; private int mDelay; private TimerTask mTimerTask; private Timer mTimer; public HostTimer(TimerTask task, int delay) { mDelay = delay; mTimerTask = task; mStatus = INIT; mIsNotified = false; mTimer = null; } /** * Mark notified. */ public void setNotified() { mIsNotified = true; } /** * Get the notification status. * * @return The notification status. */ public boolean isNotified() { return mIsNotified; } /** * Clear the status of notification. */ public void resetNotified() { mIsNotified = false; } /** * Wait on. */ public void waitOn() throws InterruptedException { Log.d("HostTimer.waitOn(): mIsNotified=" + mIsNotified + ", this=" + this); if (!mIsNotified) { wait(); } mIsNotified = false; } /** * Set the time to delay. * * @param delay The time to delay. */ public void setDelay(int delay) { mDelay = delay; } /** * Set the timer task. * * @param task The timer task. */ public void setTimerTask(TimerTask task) { mTimerTask = task; } /** * Check if the watch dog timer timed out. * * @return If timeout, return true; else return false. */ public boolean isTimeOut() { return (mStatus == TIMEOUT); } /** * Start the watch dog timer. */ public void start() { mTimer = new Timer(); mTimer.schedule(mTimerTask, mDelay); mStatus = RUNNING; } /** * Restart the watch dog timer. */ public void restart(TimerTask task, int delay) { mTimer.cancel(); mTimerTask = task; mDelay = delay; start(); } /** * Send notify to thread waiting on this object. */ public void sendNotify() { Log.d("HostTimer.sendNotify(): mIsNotified=" + mIsNotified + ", this=" + this); mIsNotified = true; notify(); } /** * Cancel the timer. To keep the status info, call this * cancel in stead of the one inherited from parent. * * @param timeout If true, the cancellation is caused by timer timing out; * If false, the cancellation is no caused by timer timing out. */ public void cancel(boolean timeout) { - mTimer.cancel(); + if (mTimer != null) { + mTimer.cancel(); + } if (mStatus == RUNNING) { if (timeout) { mStatus = TIMEOUT; } else { mStatus = CANCELLED; } } } }
true
true
public void cancel(boolean timeout) { mTimer.cancel(); if (mStatus == RUNNING) { if (timeout) { mStatus = TIMEOUT; } else { mStatus = CANCELLED; } } }
public void cancel(boolean timeout) { if (mTimer != null) { mTimer.cancel(); } if (mStatus == RUNNING) { if (timeout) { mStatus = TIMEOUT; } else { mStatus = CANCELLED; } } }
diff --git a/lenskit-eval/src/main/java/org/grouplens/lenskit/eval/metrics/predict/CoveragePredictMetric.java b/lenskit-eval/src/main/java/org/grouplens/lenskit/eval/metrics/predict/CoveragePredictMetric.java index abc60c9fe..a63ecb3c4 100644 --- a/lenskit-eval/src/main/java/org/grouplens/lenskit/eval/metrics/predict/CoveragePredictMetric.java +++ b/lenskit-eval/src/main/java/org/grouplens/lenskit/eval/metrics/predict/CoveragePredictMetric.java @@ -1,102 +1,101 @@ /* * LensKit, an open source recommender systems toolkit. * Copyright 2010-2013 Regents of the University of Minnesota and contributors * Work on LensKit has been funded by the National Science Foundation under * grants IIS 05-34939, 08-08692, 08-12148, and 10-17697. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.grouplens.lenskit.eval.metrics.predict; import com.google.common.collect.ImmutableList; import org.grouplens.lenskit.eval.algorithm.AlgorithmInstance; import org.grouplens.lenskit.eval.data.traintest.TTDataSet; import org.grouplens.lenskit.eval.metrics.AbstractTestUserMetric; import org.grouplens.lenskit.eval.metrics.TestUserMetricAccumulator; import org.grouplens.lenskit.eval.traintest.TestUser; import org.grouplens.lenskit.vectors.SparseVector; import org.grouplens.lenskit.vectors.VectorEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import java.util.List; /** * Simple evaluator that records user, rating and prediction counts and computes * recommender coverage over the queried items. * * @author <a href="http://www.grouplens.org">GroupLens Research</a> */ public class CoveragePredictMetric extends AbstractTestUserMetric { private static final Logger logger = LoggerFactory.getLogger(CoveragePredictMetric.class); private static final ImmutableList<String> COLUMNS = ImmutableList.of("NUsers", "NAttempted", "NGood", "Coverage"); private static final ImmutableList<String> USER_COLUMNS = ImmutableList.of("NAttempted", "NGood", "Coverage"); @Override public TestUserMetricAccumulator makeAccumulator(AlgorithmInstance algo, TTDataSet ds) { return new Accum(); } @Override public List<String> getColumnLabels() { return COLUMNS; } @Override public List<String> getUserColumnLabels() { return USER_COLUMNS; } class Accum implements TestUserMetricAccumulator { private int npreds = 0; private int ngood = 0; private int nusers = 0; @Nonnull @Override public Object[] evaluate(TestUser user) { SparseVector ratings = user.getTestRatings(); SparseVector predictions = user.getPredictions(); int n = 0; int good = 0; for (VectorEntry e : ratings.fast()) { - double pv = predictions.get(e.getKey()); n += 1; - if (!Double.isNaN(pv)) { + if (predictions.containsKey(e.getKey())) { good += 1; } } npreds += n; ngood += good; nusers += 1; return new Object[]{n, good, n > 0 ? (((double) good) / n) : null }; } @Nonnull @Override public Object[] finalResults() { double coverage = (double) ngood / npreds; logger.info("Coverage: {}", coverage); return new Object[]{nusers, npreds, ngood, coverage}; } } }
false
true
public Object[] evaluate(TestUser user) { SparseVector ratings = user.getTestRatings(); SparseVector predictions = user.getPredictions(); int n = 0; int good = 0; for (VectorEntry e : ratings.fast()) { double pv = predictions.get(e.getKey()); n += 1; if (!Double.isNaN(pv)) { good += 1; } } npreds += n; ngood += good; nusers += 1; return new Object[]{n, good, n > 0 ? (((double) good) / n) : null }; }
public Object[] evaluate(TestUser user) { SparseVector ratings = user.getTestRatings(); SparseVector predictions = user.getPredictions(); int n = 0; int good = 0; for (VectorEntry e : ratings.fast()) { n += 1; if (predictions.containsKey(e.getKey())) { good += 1; } } npreds += n; ngood += good; nusers += 1; return new Object[]{n, good, n > 0 ? (((double) good) / n) : null }; }
diff --git a/org.eclipse.riena.tests/src/org/eclipse/riena/navigation/ui/swt/views/ModuleGroupViewTest.java b/org.eclipse.riena.tests/src/org/eclipse/riena/navigation/ui/swt/views/ModuleGroupViewTest.java index 68e52976b..2699983fb 100644 --- a/org.eclipse.riena.tests/src/org/eclipse/riena/navigation/ui/swt/views/ModuleGroupViewTest.java +++ b/org.eclipse.riena.tests/src/org/eclipse/riena/navigation/ui/swt/views/ModuleGroupViewTest.java @@ -1,90 +1,91 @@ /******************************************************************************* * Copyright (c) 2007, 2008 compeople AG and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * compeople AG - initial API and implementation *******************************************************************************/ package org.eclipse.riena.navigation.ui.swt.views; import junit.framework.TestCase; import org.eclipse.riena.navigation.model.ModuleGroupNode; import org.eclipse.riena.navigation.model.ModuleNode; import org.eclipse.riena.navigation.model.NavigationProcessor; import org.eclipse.riena.navigation.ui.swt.lnf.renderer.ModuleGroupRenderer; import org.eclipse.riena.ui.swt.lnf.ILnfKeyConstants; import org.eclipse.riena.ui.swt.lnf.LnfManager; import org.eclipse.riena.ui.swt.lnf.rienadefault.RienaDefaultLnf; import org.eclipse.riena.ui.swt.utils.SwtUtilities; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.widgets.Shell; /** * Tests of the class {@link ModuleGroupView}. */ public class ModuleGroupViewTest extends TestCase { private ModuleGroupView view; private ModuleGroupNode node; private Shell shell; @Override protected void setUp() throws Exception { shell = new Shell(); view = new ModuleGroupView(shell, SWT.NONE); node = new ModuleGroupNode(); node.setNavigationProcessor(new NavigationProcessor()); view.bind(node); } @Override protected void tearDown() throws Exception { SwtUtilities.disposeWidget(view); SwtUtilities.disposeWidget(shell); node = null; } /** * Tests the method {@code calculateBounds(int)}. */ public void testCalculateBounds() { LnfManager.setLnf(new MyLnF()); int y = view.calculateBounds(10); assertEquals(10, y); ModuleView moduleView = new ModuleView(shell); ModuleNode moduleNode = new ModuleNode(); + node.addChild(moduleNode); moduleView.bind(moduleNode); view.registerModuleView(moduleView); y = view.calculateBounds(10); assertTrue(y > 10); FormData data = (FormData) view.getLayoutData(); assertEquals(10, data.top.offset); assertTrue((data.bottom.offset > 10) && (data.bottom.offset < y)); node.setVisible(false); y = view.calculateBounds(10); assertEquals(10, y); } private class MyLnF extends RienaDefaultLnf { @Override protected void initWidgetRendererDefaults() { getRendererTable().put(ILnfKeyConstants.MODULE_GROUP_RENDERER, new ModuleGroupRenderer()); } } }
true
true
public void testCalculateBounds() { LnfManager.setLnf(new MyLnF()); int y = view.calculateBounds(10); assertEquals(10, y); ModuleView moduleView = new ModuleView(shell); ModuleNode moduleNode = new ModuleNode(); moduleView.bind(moduleNode); view.registerModuleView(moduleView); y = view.calculateBounds(10); assertTrue(y > 10); FormData data = (FormData) view.getLayoutData(); assertEquals(10, data.top.offset); assertTrue((data.bottom.offset > 10) && (data.bottom.offset < y)); node.setVisible(false); y = view.calculateBounds(10); assertEquals(10, y); }
public void testCalculateBounds() { LnfManager.setLnf(new MyLnF()); int y = view.calculateBounds(10); assertEquals(10, y); ModuleView moduleView = new ModuleView(shell); ModuleNode moduleNode = new ModuleNode(); node.addChild(moduleNode); moduleView.bind(moduleNode); view.registerModuleView(moduleView); y = view.calculateBounds(10); assertTrue(y > 10); FormData data = (FormData) view.getLayoutData(); assertEquals(10, data.top.offset); assertTrue((data.bottom.offset > 10) && (data.bottom.offset < y)); node.setVisible(false); y = view.calculateBounds(10); assertEquals(10, y); }
diff --git a/src/cz/edu/x3m/Main.java b/src/cz/edu/x3m/Main.java index 5b59b93..f1d3531 100644 --- a/src/cz/edu/x3m/Main.java +++ b/src/cz/edu/x3m/Main.java @@ -1,115 +1,115 @@ package cz.edu.x3m; import com.gargoylesoftware.htmlunit.html.HtmlPage; import cz.edu.x3m.net.objects.Subject; import cz.edu.x3m.steps.LoggedInStep; import cz.edu.x3m.steps.LoginStep; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Jan */ public class Main { public static final Logger LOGGER = Logger.getLogger("cz.edu.x3m"); public static final File DATA = new File(".terms"); public static final long SLEEP_TIME = 2 * 60 * 1000; public Main() throws InterruptedException { while (true) { doWork(); System.out.println("Sleep"); synchronized (this) { wait(SLEEP_TIME); } } } public static void main(String[] args) throws IOException, InterruptedException { Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF); Logger.getLogger("cz.edu.x3m").setLevel(Level.OFF); new Main(); } private boolean doWork() { System.out.println("Login page"); Client client = new Client(); HtmlPage LoginPage = client.getLoginPage(); System.out.println("Logged in page"); LoginStep loginStep = new LoginStep(LoginPage); HtmlPage loggedInPage = loginStep.login(); LoggedInStep loggedInStep = new LoggedInStep(loggedInPage); if (loggedInStep.hasLoginForm()) { System.out.println("FULL"); return false; } List<cz.edu.x3m.net.objects.Subject> currTerms = loggedInStep.getTerms(); List<Subject> prevTerms = loadPrevTerms(); StageChangeResult result = TermComparator.compareSubjects(prevTerms, currTerms); System.out.println(result); - if (result.changes.isEmpty() || prevTerms.isEmpty()) { + if (result.changes.isEmpty()) { return false; } else { System.out.println(currTerms); saveCurrTerms(currTerms); System.out.println("Sending mail"); - sendEMail(result); + if (!prevTerms.isEmpty()) sendEMail(result); return true; } } private List<Subject> loadPrevTerms() { BufferedReader reader = null; List<Subject> result = new ArrayList<>(); try { reader = new BufferedReader(new FileReader(DATA)); String line; while ((line = reader.readLine()) != null) { if (line.isEmpty()) { continue; } result.add(new Subject(line)); } return result; } catch (IOException ex) { return result; } } private void saveCurrTerms(List<Subject> items) { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(DATA)); for (int i = 0; i < items.size(); i++) { Subject subject = items.get(i); writer.write(subject.asOutput()); writer.newLine(); } writer.close(); } catch (IOException ex) { return; } } private void sendEMail(StageChangeResult result) { Client c = new Client(); c.getSendEmailPage(result); } }
false
true
private boolean doWork() { System.out.println("Login page"); Client client = new Client(); HtmlPage LoginPage = client.getLoginPage(); System.out.println("Logged in page"); LoginStep loginStep = new LoginStep(LoginPage); HtmlPage loggedInPage = loginStep.login(); LoggedInStep loggedInStep = new LoggedInStep(loggedInPage); if (loggedInStep.hasLoginForm()) { System.out.println("FULL"); return false; } List<cz.edu.x3m.net.objects.Subject> currTerms = loggedInStep.getTerms(); List<Subject> prevTerms = loadPrevTerms(); StageChangeResult result = TermComparator.compareSubjects(prevTerms, currTerms); System.out.println(result); if (result.changes.isEmpty() || prevTerms.isEmpty()) { return false; } else { System.out.println(currTerms); saveCurrTerms(currTerms); System.out.println("Sending mail"); sendEMail(result); return true; } }
private boolean doWork() { System.out.println("Login page"); Client client = new Client(); HtmlPage LoginPage = client.getLoginPage(); System.out.println("Logged in page"); LoginStep loginStep = new LoginStep(LoginPage); HtmlPage loggedInPage = loginStep.login(); LoggedInStep loggedInStep = new LoggedInStep(loggedInPage); if (loggedInStep.hasLoginForm()) { System.out.println("FULL"); return false; } List<cz.edu.x3m.net.objects.Subject> currTerms = loggedInStep.getTerms(); List<Subject> prevTerms = loadPrevTerms(); StageChangeResult result = TermComparator.compareSubjects(prevTerms, currTerms); System.out.println(result); if (result.changes.isEmpty()) { return false; } else { System.out.println(currTerms); saveCurrTerms(currTerms); System.out.println("Sending mail"); if (!prevTerms.isEmpty()) sendEMail(result); return true; } }
diff --git a/api/src/main/java/com/github/podd/utils/OntologyUtils.java b/api/src/main/java/com/github/podd/utils/OntologyUtils.java index f248a18f..5957b42e 100644 --- a/api/src/main/java/com/github/podd/utils/OntologyUtils.java +++ b/api/src/main/java/com/github/podd/utils/OntologyUtils.java @@ -1,840 +1,843 @@ /** * PODD is an OWL ontology database used for scientific project management * * Copyright (C) 2009-2013 The University Of Queensland * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package com.github.podd.utils; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.openrdf.OpenRDFException; import org.openrdf.model.Model; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.LinkedHashModel; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.model.util.GraphUtil; import org.openrdf.model.util.GraphUtilException; import org.openrdf.model.util.ModelException; import org.openrdf.model.vocabulary.OWL; import org.openrdf.model.vocabulary.RDF; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandler; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.Rio; import org.openrdf.rio.UnsupportedRDFormatException; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLOntologyID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.podd.exception.SchemaManifestException; import com.github.podd.exception.UnmanagedArtifactIRIException; import com.github.podd.exception.UnmanagedArtifactVersionException; /** * Utilities for working with {@link InferredOWLOntologyID} * * @author Peter Ansell [email protected] */ public class OntologyUtils { private static final Logger log = LoggerFactory.getLogger(OntologyUtils.class); /** * Extracts ontology and version IRIs to separate sets, which are both given as parameters. * * Only recognises ontology IRIs which have an "ontologyIRI, rdf:type, owl:Ontology" triple. * * Only recognises version IRIs which have both "versionIRI, rdf:type, owl:Ontology" and * "ontologyIRI, owl:versionIRI, versionIRI" * * @param model * The input statements. * @param schemaOntologyUris * An output container for all of the ontology IRIs which are not also version IRIs. * @param schemaVersionUris * An output container for all of the ontology IRIs which are also versionIRIs. */ public static void extractOntologyAndVersions(final Model model, final Set<URI> schemaOntologyUris, final Set<URI> schemaVersionUris) { for(final Statement nextImport : model.filter(null, OWL.VERSIONIRI, null)) { if(nextImport.getObject() instanceof URI) { if(!model.contains((URI)nextImport.getObject(), RDF.TYPE, OWL.ONTOLOGY)) { model.add((URI)nextImport.getObject(), RDF.TYPE, OWL.ONTOLOGY); } } } for(final Resource nextOntology : model.filter(null, RDF.TYPE, OWL.ONTOLOGY).subjects()) { if(nextOntology instanceof URI) { if(model.contains(null, OWL.VERSIONIRI, nextOntology)) { schemaVersionUris.add((URI)nextOntology); } else { schemaOntologyUris.add((URI)nextOntology); } } } } /** * Retrieves imports specified using {@link OWL#IMPORTS}, based on the given version IRIs. Also * checks to verify that there is an {@link OWL#VERSIONIRI} statement for each of the version * IRIs. <br> * This works with the format used by both the schema manifests and the schema management graph. * * @param model * @param schemaVersionUris * @return * @throws SchemaManifestException */ public static Map<URI, Set<OWLOntologyID>> getSchemaManifestImports(final Model model, final Set<URI> schemaOntologyUris, final Set<URI> schemaVersionUris) throws SchemaManifestException { final ConcurrentMap<URI, Set<OWLOntologyID>> result = new ConcurrentHashMap<>(); final ConcurrentMap<URI, Set<URI>> importsMap = new ConcurrentHashMap<>(schemaOntologyUris.size()); if(schemaVersionUris.isEmpty()) { log.debug("No schema version URIs to get imports for"); } for(final URI nextSchemaVersionUri : schemaVersionUris) { final Set<Resource> ontologies = model.filter(null, OWL.VERSIONIRI, nextSchemaVersionUri).subjects(); if(ontologies.isEmpty()) { throw new SchemaManifestException(IRI.create(nextSchemaVersionUri), "No mapping from version IRI to an ontology IRI"); } if(ontologies.size() > 1) { OntologyUtils.log.error("Found multiple mappings from version IRI to ontology IRI: {} {}", nextSchemaVersionUri, ontologies); throw new SchemaManifestException(IRI.create(nextSchemaVersionUri), "Non-unique mapping from version IRI to an ontology IRI"); } final Resource uniqueOntology = ontologies.iterator().next(); if(!(uniqueOntology instanceof URI)) { OntologyUtils.log.error("Found non-URI mapping from version IRI to ontology IRI: {} {}", nextSchemaVersionUri, ontologies); throw new SchemaManifestException(IRI.create(nextSchemaVersionUri), "Non-URI mapping from version IRI to an ontology IRI"); } final Set<Value> imports = model.filter(nextSchemaVersionUri, OWL.IMPORTS, null).objects(); Set<OWLOntologyID> nextSet = new LinkedHashSet<>(); final Set<OWLOntologyID> putIfAbsent = result.putIfAbsent(nextSchemaVersionUri, nextSet); if(putIfAbsent != null) { nextSet = putIfAbsent; } Set<URI> nextImports = new LinkedHashSet<>(); for(final Value nextImport : imports) { if(!(nextImport instanceof URI)) { OntologyUtils.log.error("Found non-URI import for version IRI: {} {}", nextSchemaVersionUri, nextImport); throw new SchemaManifestException(IRI.create(nextSchemaVersionUri), "Non-URI import for version IRI"); } final URI nextImportVersionURI = (URI)nextImport; nextImports.add(nextImportVersionURI); } List<URI> orderImports = OntologyUtils.orderImports(model, schemaOntologyUris, schemaVersionUris, importsMap); // Iterate through universally ordered collection to find ordered imports for this // ontology // TODO: This may not be the most efficient way to do this for(URI nextOrderedVersion : orderImports) { if(nextImports.contains(nextOrderedVersion)) { try { final URI nextImportOntologyURI = GraphUtil.getUniqueSubjectURI(model, OWL.VERSIONIRI, nextOrderedVersion); nextSet.add(new OWLOntologyID(nextImportOntologyURI, nextOrderedVersion)); } catch(final GraphUtilException e) { OntologyUtils.log.error("Found non-unique ontology IRI for imported version IRI: {}", nextOrderedVersion); throw new SchemaManifestException(IRI.create(nextOrderedVersion), "Non-URI import for version IRI"); } } } } return result; } /** * @param model * @param currentVersionsMap * @param allVersionsMap * @param nextSchemaOntologyUri */ public static void mapAllVersions(final Model model, final ConcurrentMap<URI, URI> currentVersionsMap, final ConcurrentMap<URI, Set<URI>> allVersionsMap, final URI nextSchemaOntologyUri) { final Set<Value> allVersions = model.filter(nextSchemaOntologyUri, OWL.VERSIONIRI, null).objects(); Set<URI> nextAllVersions = new HashSet<>(); final Set<URI> putIfAbsent = allVersionsMap.putIfAbsent(nextSchemaOntologyUri, nextAllVersions); if(putIfAbsent != null) { nextAllVersions = putIfAbsent; } // If they specified a current version add it to the set if(currentVersionsMap.containsKey(nextSchemaOntologyUri)) { nextAllVersions.add(currentVersionsMap.get(nextSchemaOntologyUri)); } for(final Value nextVersionURI : allVersions) { if(nextVersionURI instanceof URI) { nextAllVersions.add((URI)nextVersionURI); } else { OntologyUtils.log.error("Version was not a URI: {} {}", nextSchemaOntologyUri, nextVersionURI); } } if(nextAllVersions.isEmpty()) { OntologyUtils.log.debug("Could not find any version information for schema ontology: {}", nextSchemaOntologyUri); } } /** * @param model * @param currentVersionsMap * @param allVersionsMap * @param importsMap * @param importOrder * @param nextOntologyUri */ public static void mapAndSortImports(final Model model, final ConcurrentMap<URI, URI> currentVersionsMap, final ConcurrentMap<URI, Set<URI>> allVersionsMap, final ConcurrentMap<URI, Set<URI>> importsMap, final List<URI> importOrder, final URI nextOntologyUri) { final Set<Value> imports = model.filter(nextOntologyUri, OWL.IMPORTS, null).objects(); Set<URI> nextImportsSet = new LinkedHashSet<>(); final Set<URI> putIfAbsent = importsMap.putIfAbsent(nextOntologyUri, nextImportsSet); if(putIfAbsent != null) { nextImportsSet = putIfAbsent; } int maxIndex = 0; if(imports.isEmpty()) { if(!nextImportsSet.isEmpty()) { OntologyUtils.log.error("Found inconsistent imports set: {} {}", nextOntologyUri, nextImportsSet); } } else { for(final Value nextImport : imports) { if(nextImport instanceof URI) { if(nextImportsSet.contains(nextImport)) { // avoid duplicates continue; } if(currentVersionsMap.containsKey(nextImport)) { // Map down to the current version to ensure that we can load multiple // versions simultaneously (if possible with the rest of the system) nextImportsSet.add(currentVersionsMap.get(nextImport)); } else if(currentVersionsMap.containsValue(nextImport)) { nextImportsSet.add((URI)nextImport); } else { boolean foundAllVersion = false; // Attempt to verify if the version exists for(final Entry<URI, Set<URI>> nextEntry : allVersionsMap.entrySet()) { final URI nextAllVersions = nextEntry.getKey(); if(nextAllVersions.equals(nextImport)) { // TODO: Should we fail if we are importing ontologies without // current versions, such as this case if(nextEntry.getValue().isEmpty()) { nextImportsSet.add((URI)nextImport); } else { // Randomly choose one, as the ontology does not have a current // version, but it does have some version information // TODO: Should we just use the import instead of randomly // choosing here nextImportsSet.add(nextEntry.getValue().iterator().next()); } foundAllVersion = true; + break; } else if(nextEntry.getValue().contains(nextImport)) { nextImportsSet.add((URI)nextImport); foundAllVersion = true; + break; } } if(!foundAllVersion) { OntologyUtils.log.warn("Could not find import: {} imports {}", nextOntologyUri, nextImport); } else { - nextImportsSet.add((URI)nextImport); + // This should not be necessary given the sequence of calls above + //nextImportsSet.add((URI)nextImport); } } final int nextIndex = importOrder.indexOf(nextImport); if(nextIndex >= maxIndex) { maxIndex = nextIndex + 1; } } } } OntologyUtils.log.debug("adding import for {} at {}", nextOntologyUri, maxIndex); // TODO: FIXME: This will not allow for multiple versions of a single schema ontology at the // same time if they have any shared import versions importOrder.add(maxIndex, nextOntologyUri); } /** * @param model * @param currentVersionsMap * @param nextSchemaOntologyUri * @throws SchemaManifestException */ public static void mapCurrentVersion(final Model model, final ConcurrentMap<URI, URI> currentVersionsMap, final URI nextSchemaOntologyUri) throws SchemaManifestException { try { final URI nextCurrentVersionURI = model.filter(nextSchemaOntologyUri, PODD.OMV_CURRENT_VERSION, null).objectURI(); if(nextCurrentVersionURI == null) { // OntologyUtils.log // .error("Did not find a current version for schema ontology: {}", // nextSchemaOntologyUri); // throw new SchemaManifestException(IRI.create(nextSchemaOntologyUri), // "Did not find a current version for schema ontology: " + // nextSchemaOntologyUri.stringValue()); } else { final URI putIfAbsent = currentVersionsMap.putIfAbsent(nextSchemaOntologyUri, nextCurrentVersionURI); if(putIfAbsent != null) { OntologyUtils.log.error("Found multiple version URIs for ontology: {} old={} new={}", nextSchemaOntologyUri, putIfAbsent, nextCurrentVersionURI); throw new SchemaManifestException(IRI.create(nextSchemaOntologyUri), "Found multiple version IRIs for ontology"); } } } catch(final ModelException e) { OntologyUtils.log.error("Could not find a single unique current version for schema ontology: {}", nextSchemaOntologyUri); throw new SchemaManifestException(IRI.create(nextSchemaOntologyUri), "Could not find a single unique current version IRI for schema ontology"); } } /** * Extracts the {@link InferredOWLOntologyID} instances that are represented as RDF * {@link Statement}s in the given {@link Model}. * * @param input * The input model containing RDF statements. * @return A Collection of {@link InferredOWLOntologyID} instances derived from the statements * in the model. */ public static List<InferredOWLOntologyID> modelToOntologyIDs(final Model input) { return OntologyUtils.modelToOntologyIDs(input, false, true); } /** * Extracts the {@link InferredOWLOntologyID} instances that are represented as RDF * {@link Statement}s in the given {@link Model}. * * @param input * The input model containing RDF statements. * @param allowVersionless * True if the algorithm should recognise versionless ontologies, and false to ignore * them. * @return A Collection of {@link InferredOWLOntologyID} instances derived from the statements * in the model. */ public static List<InferredOWLOntologyID> modelToOntologyIDs(final Model input, final boolean allowVersionless, final boolean includeInferred) { final List<InferredOWLOntologyID> results = new ArrayList<InferredOWLOntologyID>(); final Model typedOntologies = input.filter(null, RDF.TYPE, OWL.ONTOLOGY); for(final Statement nextTypeStatement : typedOntologies) { if(nextTypeStatement.getSubject() instanceof URI) { final Model versions = input.filter(nextTypeStatement.getSubject(), OWL.VERSIONIRI, null); if(versions.isEmpty()) { if(allowVersionless) { results.add(new InferredOWLOntologyID(IRI.create((URI)nextTypeStatement.getSubject()), null, null)); } } else { for(final Statement nextVersion : versions) { if(nextVersion.getObject() instanceof URI) { final Model inferredOntologies = input.filter((URI)nextVersion.getObject(), PODD.PODD_BASE_INFERRED_VERSION, null); if(!includeInferred) { results.add(new InferredOWLOntologyID((URI)nextTypeStatement.getSubject(), (URI)nextVersion.getObject(), null)); } else { if(inferredOntologies.isEmpty()) { // If there were no poddBase#inferredVersion statements, backup // by // trying to infer the versions using owl:imports final Model importsOntologies = input.filter(null, OWL.IMPORTS, nextVersion.getObject()); if(importsOntologies.isEmpty()) { results.add(new InferredOWLOntologyID((URI)nextTypeStatement.getSubject(), (URI)nextVersion.getObject(), null)); } else { for(final Statement nextImportOntology : importsOntologies) { if(nextImportOntology.getSubject() instanceof URI) { results.add(new InferredOWLOntologyID((URI)nextTypeStatement .getSubject(), (URI)nextVersion.getObject(), (URI)nextImportOntology.getSubject())); } else { OntologyUtils.log.error("Found a non-URI import statement: {}", nextImportOntology); } } } } else { for(final Statement nextInferredOntology : inferredOntologies) { if(nextInferredOntology.getObject() instanceof URI) { results.add(new InferredOWLOntologyID((URI)nextTypeStatement.getSubject(), (URI)nextVersion.getObject(), (URI)nextInferredOntology.getObject())); } } } } } } } } } return results; } /** * Serialises the given collection of {@link InferredOWLOntologyID} objects to RDF, adding the * {@link Statement}s to the given {@link RDFHandler}. * <p> * This method wraps the serialisation from {@link InferredOWLOntologyID#toRDF()}. * * @param input * The collection of {@link InferredOWLOntologyID} objects to render to RDF. * @param handler * The handler for handling the RDF statements. * @throws RDFHandlerException * If there is an error while handling the statements. */ public static void ontologyIDsToHandler(final Collection<InferredOWLOntologyID> input, final RDFHandler handler) throws RDFHandlerException { for(final InferredOWLOntologyID nextOntology : input) { for(final Statement nextStatement : nextOntology.toRDF()) { handler.handleStatement(nextStatement); } } } /** * Serialises the given collection of {@link InferredOWLOntologyID} objects to RDF, adding the * {@link Statement}s to the given {@link Model}, or creating a new Model if the given model is * null. * <p> * This method wraps the serialisation from {@link InferredOWLOntologyID#toRDF()}. * * @param input * The collection of {@link InferredOWLOntologyID} objects to render to RDF. * @param result * The Model to contain the resulting statements, or null to have one created * internally * @param includeInferredOntologyStatements * @return A model containing the RDF statements about the given ontologies. * @throws RDFHandlerException * If there is an error while handling the statements. */ public static Model ontologyIDsToModel(final Collection<InferredOWLOntologyID> input, final Model result, final boolean includeInferredOntologyStatements) { Model results = result; if(results == null) { results = new LinkedHashModel(); } for(final InferredOWLOntologyID nextOntology : input) { OntologyUtils.ontologyIDToRDF(nextOntology, results, includeInferredOntologyStatements); } return results; } public static Model ontologyIDsToModel(final Collection<InferredOWLOntologyID> input, final Model result) { return OntologyUtils.ontologyIDsToModel(input, result, true); } public static Model ontologyIDToRDF(final OWLOntologyID ontology, final Model result, final boolean includeInferredOntologyStatements) { final ValueFactory vf = ValueFactoryImpl.getInstance(); if(ontology.getOntologyIRI() != null) { result.add(vf.createStatement(ontology.getOntologyIRI().toOpenRDFURI(), RDF.TYPE, OWL.ONTOLOGY)); if(ontology.getVersionIRI() != null) { result.add(vf.createStatement(ontology.getVersionIRI().toOpenRDFURI(), RDF.TYPE, OWL.ONTOLOGY)); result.add(vf.createStatement(ontology.getOntologyIRI().toOpenRDFURI(), OWL.VERSIONIRI, ontology .getVersionIRI().toOpenRDFURI())); if(includeInferredOntologyStatements && ontology instanceof InferredOWLOntologyID) { final InferredOWLOntologyID inferredOntology = (InferredOWLOntologyID)ontology; if(inferredOntology.getInferredOntologyIRI() != null) { result.add(vf.createStatement(inferredOntology.getInferredOntologyIRI().toOpenRDFURI(), RDF.TYPE, OWL.ONTOLOGY)); result.add(vf.createStatement(inferredOntology.getVersionIRI().toOpenRDFURI(), PODD.PODD_BASE_INFERRED_VERSION, inferredOntology.getInferredOntologyIRI() .toOpenRDFURI())); } } } } return result; } /** * Orders the schema ontology imports into list that can be uploaded in order to give a good * chance that dependencies will be uploaded first. * * @param model * @param schemaOntologyUris * @param schemaVersionUris * @return An ordered list of {@link URI}s that determine a useful order for uploading schema * ontologies to ensure that dependencies are available internally when needed. * @throws SchemaManifestException */ public static List<URI> orderImports(final Model model, final Set<URI> schemaOntologyUris, final Set<URI> schemaVersionUris, final ConcurrentMap<URI, Set<URI>> importsMap) throws SchemaManifestException { final List<URI> importOrder = new ArrayList<>(schemaOntologyUris.size()); final ConcurrentMap<URI, URI> currentVersionsMap = new ConcurrentHashMap<>(schemaOntologyUris.size()); final ConcurrentMap<URI, Set<URI>> allVersionsMap = new ConcurrentHashMap<>(schemaOntologyUris.size()); // Find current version for each schema ontology for(final URI nextSchemaOntologyUri : schemaOntologyUris) { OntologyUtils.mapCurrentVersion(model, currentVersionsMap, nextSchemaOntologyUri); } // Find all versions for each schema ontology for(final URI nextSchemaOntologyUri : schemaOntologyUris) { OntologyUtils.mapAllVersions(model, currentVersionsMap, allVersionsMap, nextSchemaOntologyUri); } // Map the actual schema ontologies to the correct order, based on // current versions and all versions with the imports taken into account for(final URI nextVersionUri : schemaVersionUris) { OntologyUtils.mapAndSortImports(model, currentVersionsMap, allVersionsMap, importsMap, importOrder, nextVersionUri); } OntologyUtils.log.debug("importOrder: {}", importOrder); return importOrder; } /** * Extracts the {@link InferredOWLOntologyID} instances that are represented as RDF * {@link Statement}s in the given {@link String}. * * @param string * The input string containing RDF statements. * @param format * The format of RDF statements in the string * @return A Collection of {@link InferredOWLOntologyID} instances derived from the statements * in the string. * @throws OpenRDFException * @throws IOException */ public static Collection<InferredOWLOntologyID> stringToOntologyID(final String string, final RDFFormat format) throws OpenRDFException, IOException { final Model model = Rio.parse(new StringReader(string), "", format); return OntologyUtils.modelToOntologyIDs(model); } /** * This method performs a consistency check between the ontology imports specified in the * schema-manifest with the actual imports specified within the ontology. * * If the two sets of imports are not equal, a {@link SchemaManifestException} is thrown. * * @param manifestModel * Contents of the schema-manifest * @param schemaVersionUris * Ontology Version IRIs to be loaded * @throws IOException * @throws RDFParseException * @throws UnsupportedRDFormatException * @throws SchemaManifestException * If the imports from the two locations are not consistent */ public static void validateSchemaManifestImports(final Model manifestModel, final Set<URI> schemaOntologyUris, final Set<URI> schemaVersionUris) throws IOException, RDFParseException, UnsupportedRDFormatException, SchemaManifestException { for(final URI nextOntologyUri : schemaOntologyUris) { if(manifestModel.contains(nextOntologyUri, OWL.IMPORTS, null)) { OntologyUtils.log.error("Schema ontology in manifest has owl:imports coming directly from it: {}", nextOntologyUri); throw new SchemaManifestException(IRI.create(nextOntologyUri), "Schema ontology in manifest has owl:imports coming directly from it"); } Model currentVersion = manifestModel.filter(nextOntologyUri, PODD.OMV_CURRENT_VERSION, null); if(currentVersion.isEmpty()) { OntologyUtils.log.error("Missing OMV current version for schema ontology: {}", nextOntologyUri); throw new SchemaManifestException(IRI.create(nextOntologyUri), "Missing OMV current version for schema ontology"); } if(currentVersion.size() > 1) { OntologyUtils.log.error("Multiple OMV current versions for schema ontology: {}", nextOntologyUri); throw new SchemaManifestException(IRI.create(nextOntologyUri), "Multiple OMV current versions for schema ontology"); } } for(final URI nextVersionUri : schemaVersionUris) { final Set<Value> importsInManifest = manifestModel.filter(nextVersionUri, OWL.IMPORTS, null).objects(); final String classpathLocation = manifestModel.filter(nextVersionUri, PODD.PODD_SCHEMA_CLASSPATH, null).objectLiteral() .stringValue(); final RDFFormat format = Rio.getParserFormatForFileName(classpathLocation, RDFFormat.RDFXML); try (final InputStream input = OntologyUtils.class.getResourceAsStream(classpathLocation);) { if(input == null) { throw new SchemaManifestException(IRI.create(nextVersionUri), "Could not find schema at designated classpath location: " + nextVersionUri.stringValue()); } final Model model = Rio.parse(input, "", format); final Set<Value> importsInOwlFile = model.filter(null, OWL.IMPORTS, null).objects(); OntologyUtils.log.debug("Comparing: \n Manifest: {} \n Owl: {}", importsInManifest, importsInOwlFile); if(!importsInManifest.equals(importsInOwlFile)) { throw new SchemaManifestException(IRI.create(nextVersionUri), "Schema manifest imports not consistent with actual imports"); } } } } /** * Finds the schema imports for the given artifact. * * Must not throw an {@link UnmanagedArtifactIRIException} or * {@link UnmanagedArtifactVersionException} if the artifact does not exist globally, as long as * it is managed correctly in the given model. * * @param artifactID * @param results * @param model * @throws OpenRDFException * @throws SchemaManifestException * @throws IOException * @throws RDFParseException * @throws UnsupportedRDFormatException */ public static Set<OWLOntologyID> getArtifactImports(final InferredOWLOntologyID artifactID, final Model model) throws OpenRDFException, SchemaManifestException, IOException, RDFParseException, UnsupportedRDFormatException { Objects.requireNonNull(artifactID); Objects.requireNonNull(model); final Set<OWLOntologyID> results = new LinkedHashSet<OWLOntologyID>(); final Set<URI> schemaOntologyUris = new HashSet<>(); final Set<URI> schemaVersionUris = new HashSet<>(); final ConcurrentMap<URI, Set<URI>> importsMap = new ConcurrentHashMap<>(schemaOntologyUris.size()); OntologyUtils.extractOntologyAndVersions(model, schemaOntologyUris, schemaVersionUris); List<InferredOWLOntologyID> ontologyIDs = OntologyUtils.modelToOntologyIDs(model, true, false); if(schemaOntologyUris.contains(artifactID.getOntologyIRI().toOpenRDFURI())) { List<URI> importsForOneOntology = orderImports(model, schemaOntologyUris, schemaVersionUris, importsMap); importsForOneOntology.remove(artifactID.getOntologyIRI().toOpenRDFURI()); if(artifactID.getVersionIRI() != null) { importsForOneOntology.remove(artifactID.getVersionIRI().toOpenRDFURI()); } if(artifactID.getInferredOntologyIRI() != null) { importsForOneOntology.remove(artifactID.getInferredOntologyIRI().toOpenRDFURI()); } for(URI nextImport : importsForOneOntology) { if(importsMap.containsKey(nextImport)) { for(OWLOntologyID nextOntologyID : ontologyIDs) { if(nextOntologyID.getOntologyIRI().toOpenRDFURI().equals(nextImport)) { results.add(nextOntologyID); break; } else if(nextOntologyID.getVersionIRI() != null && nextOntologyID.getVersionIRI().toOpenRDFURI().equals(nextImport)) { results.add(nextOntologyID); break; } } } } } else { throw new SchemaManifestException(artifactID.getOntologyIRI(), "Did not find the given ontology IRI in the model"); } return results; } private OntologyUtils() { } }
false
true
public static void mapAndSortImports(final Model model, final ConcurrentMap<URI, URI> currentVersionsMap, final ConcurrentMap<URI, Set<URI>> allVersionsMap, final ConcurrentMap<URI, Set<URI>> importsMap, final List<URI> importOrder, final URI nextOntologyUri) { final Set<Value> imports = model.filter(nextOntologyUri, OWL.IMPORTS, null).objects(); Set<URI> nextImportsSet = new LinkedHashSet<>(); final Set<URI> putIfAbsent = importsMap.putIfAbsent(nextOntologyUri, nextImportsSet); if(putIfAbsent != null) { nextImportsSet = putIfAbsent; } int maxIndex = 0; if(imports.isEmpty()) { if(!nextImportsSet.isEmpty()) { OntologyUtils.log.error("Found inconsistent imports set: {} {}", nextOntologyUri, nextImportsSet); } } else { for(final Value nextImport : imports) { if(nextImport instanceof URI) { if(nextImportsSet.contains(nextImport)) { // avoid duplicates continue; } if(currentVersionsMap.containsKey(nextImport)) { // Map down to the current version to ensure that we can load multiple // versions simultaneously (if possible with the rest of the system) nextImportsSet.add(currentVersionsMap.get(nextImport)); } else if(currentVersionsMap.containsValue(nextImport)) { nextImportsSet.add((URI)nextImport); } else { boolean foundAllVersion = false; // Attempt to verify if the version exists for(final Entry<URI, Set<URI>> nextEntry : allVersionsMap.entrySet()) { final URI nextAllVersions = nextEntry.getKey(); if(nextAllVersions.equals(nextImport)) { // TODO: Should we fail if we are importing ontologies without // current versions, such as this case if(nextEntry.getValue().isEmpty()) { nextImportsSet.add((URI)nextImport); } else { // Randomly choose one, as the ontology does not have a current // version, but it does have some version information // TODO: Should we just use the import instead of randomly // choosing here nextImportsSet.add(nextEntry.getValue().iterator().next()); } foundAllVersion = true; } else if(nextEntry.getValue().contains(nextImport)) { nextImportsSet.add((URI)nextImport); foundAllVersion = true; } } if(!foundAllVersion) { OntologyUtils.log.warn("Could not find import: {} imports {}", nextOntologyUri, nextImport); } else { nextImportsSet.add((URI)nextImport); } } final int nextIndex = importOrder.indexOf(nextImport); if(nextIndex >= maxIndex) { maxIndex = nextIndex + 1; } } } } OntologyUtils.log.debug("adding import for {} at {}", nextOntologyUri, maxIndex); // TODO: FIXME: This will not allow for multiple versions of a single schema ontology at the // same time if they have any shared import versions importOrder.add(maxIndex, nextOntologyUri); }
public static void mapAndSortImports(final Model model, final ConcurrentMap<URI, URI> currentVersionsMap, final ConcurrentMap<URI, Set<URI>> allVersionsMap, final ConcurrentMap<URI, Set<URI>> importsMap, final List<URI> importOrder, final URI nextOntologyUri) { final Set<Value> imports = model.filter(nextOntologyUri, OWL.IMPORTS, null).objects(); Set<URI> nextImportsSet = new LinkedHashSet<>(); final Set<URI> putIfAbsent = importsMap.putIfAbsent(nextOntologyUri, nextImportsSet); if(putIfAbsent != null) { nextImportsSet = putIfAbsent; } int maxIndex = 0; if(imports.isEmpty()) { if(!nextImportsSet.isEmpty()) { OntologyUtils.log.error("Found inconsistent imports set: {} {}", nextOntologyUri, nextImportsSet); } } else { for(final Value nextImport : imports) { if(nextImport instanceof URI) { if(nextImportsSet.contains(nextImport)) { // avoid duplicates continue; } if(currentVersionsMap.containsKey(nextImport)) { // Map down to the current version to ensure that we can load multiple // versions simultaneously (if possible with the rest of the system) nextImportsSet.add(currentVersionsMap.get(nextImport)); } else if(currentVersionsMap.containsValue(nextImport)) { nextImportsSet.add((URI)nextImport); } else { boolean foundAllVersion = false; // Attempt to verify if the version exists for(final Entry<URI, Set<URI>> nextEntry : allVersionsMap.entrySet()) { final URI nextAllVersions = nextEntry.getKey(); if(nextAllVersions.equals(nextImport)) { // TODO: Should we fail if we are importing ontologies without // current versions, such as this case if(nextEntry.getValue().isEmpty()) { nextImportsSet.add((URI)nextImport); } else { // Randomly choose one, as the ontology does not have a current // version, but it does have some version information // TODO: Should we just use the import instead of randomly // choosing here nextImportsSet.add(nextEntry.getValue().iterator().next()); } foundAllVersion = true; break; } else if(nextEntry.getValue().contains(nextImport)) { nextImportsSet.add((URI)nextImport); foundAllVersion = true; break; } } if(!foundAllVersion) { OntologyUtils.log.warn("Could not find import: {} imports {}", nextOntologyUri, nextImport); } else { // This should not be necessary given the sequence of calls above //nextImportsSet.add((URI)nextImport); } } final int nextIndex = importOrder.indexOf(nextImport); if(nextIndex >= maxIndex) { maxIndex = nextIndex + 1; } } } } OntologyUtils.log.debug("adding import for {} at {}", nextOntologyUri, maxIndex); // TODO: FIXME: This will not allow for multiple versions of a single schema ontology at the // same time if they have any shared import versions importOrder.add(maxIndex, nextOntologyUri); }
diff --git a/cdi/plugins/org.jboss.tools.cdi.core/src/org/jboss/tools/cdi/internal/core/impl/definition/MethodDefinition.java b/cdi/plugins/org.jboss.tools.cdi.core/src/org/jboss/tools/cdi/internal/core/impl/definition/MethodDefinition.java index 7f256efdc..e37d4d03f 100644 --- a/cdi/plugins/org.jboss.tools.cdi.core/src/org/jboss/tools/cdi/internal/core/impl/definition/MethodDefinition.java +++ b/cdi/plugins/org.jboss.tools.cdi.core/src/org/jboss/tools/cdi/internal/core/impl/definition/MethodDefinition.java @@ -1,313 +1,313 @@ /******************************************************************************* * Copyright (c) 2009 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.cdi.internal.core.impl.definition; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.jboss.tools.cdi.core.CDIConstants; import org.jboss.tools.cdi.core.IAnnotationDeclaration; import org.jboss.tools.cdi.core.IInterceptorBinding; import org.jboss.tools.cdi.core.IInterceptorBindingDeclaration; import org.jboss.tools.cdi.core.IRootDefinitionContext; import org.jboss.tools.cdi.core.IStereotypeDeclaration; import org.jboss.tools.cdi.internal.core.impl.AnnotationDeclaration; import org.jboss.tools.cdi.internal.core.impl.ClassBean; import org.jboss.tools.cdi.internal.core.impl.ParametedType; import org.jboss.tools.common.model.project.ext.impl.ValueInfo; import org.jboss.tools.common.model.util.EclipseJavaUtil; /** * * @author Viacheslav Kabanovich * */ public class MethodDefinition extends BeanMemberDefinition { IMethod method; boolean isConstructor; List<ParameterDefinition> parameters = new ArrayList<ParameterDefinition>(); public MethodDefinition() {} public void setMethod(IMethod method, IRootDefinitionContext context) { this.method = method; setAnnotatable(method, method.getDeclaringType(), context); } public IMethod getMethod() { return method; } public boolean isConstructor() { return isConstructor; } protected void init(IType contextType, IRootDefinitionContext context) throws CoreException { super.init(contextType, context); isConstructor = method.isConstructor(); //TODO process parameters for disposers and observers loadParamDefinitions(contextType, context); } public boolean parametersAreInjectionPoints() { return getProducesAnnotation() != null || getInjectAnnotation() != null; } void loadParamDefinitions(IType contextType, IRootDefinitionContext context) throws CoreException { if(method == null) return; boolean parametersAreInjectionPoints = parametersAreInjectionPoints(); String[] parameterNames = method.getParameterNames(); if(parameterNames == null || parameterNames.length == 0) return; if(contextType == null || contextType.isBinary()) return; String content = typeDefinition.getContent(); if(content == null) return; ISourceRange range = method.getSourceRange(); ISourceRange nameRange = method.getNameRange(); if(nameRange != null) range = nameRange; int paramStart = content.indexOf('(', range.getOffset()); if(paramStart < 0) return; int declEnd = content.indexOf('{', paramStart); if(declEnd < 0) return; int paramEnd = content.lastIndexOf(')', declEnd); - if(paramEnd < 0) return; + if(paramEnd < paramStart) paramEnd = declEnd; String paramsString = content.substring(paramStart + 1, paramEnd); if(!parametersAreInjectionPoints && paramsString.indexOf("@Observes") >= 0) { parametersAreInjectionPoints = true; } if(!parametersAreInjectionPoints && paramsString.indexOf('@') < 0) return; String[] params = getParams(paramsString); String[] ps = method.getParameterTypes(); int start = paramStart + 1; for (int i = 0; i < params.length; i++) { if(ps.length <= i) { // CDICorePlugin.getDefault().logError(new IllegalArgumentException("Cannot parse method parameters for " + paramsString)); // The source code may be broken. Just ignore such errors. break; } if(!parametersAreInjectionPoints && params[i].indexOf('@') < 0) { start += params[i].length() + 1; continue; //do not need parameters without annotation } ParameterDefinition pd = new ParameterDefinition(); ParametedType type = context.getProject().getTypeFactory().getParametedType(method, ps[i]); pd.methodDefinition = this; pd.name = parameterNames[i]; pd.index = i; pd.type = type; String p = params[i].trim(); int pi = params[i].indexOf(p); ValueInfo v = new CheckingValueInfo(method); v.setValue(params[i]); v.valueStartPosition = start + pi; v.valueLength = p.length(); pd.setPosition(v); String[] tokens = getParamTokens(p); for (String q: tokens) { if(!q.startsWith("@")) continue; v = new CheckingValueInfo(method); v.setValue(q); v.valueStartPosition = start + params[i].indexOf(q); v.valueLength = q.length(); int s = q.indexOf('('); if(s >= 0) q = q.substring(0, s).trim(); String annotationType = EclipseJavaUtil.resolveType(contextType, q.substring(1).trim()); if(annotationType != null) pd.annotationsByTypeName.put(annotationType, v); } parameters.add(pd); start += params[i].length() + 1; } } @Override public boolean isCDIAnnotated() { return super.isCDIAnnotated() || isDisposer() || isObserver() || getPreDestroyMethod() != null || getPostConstructorMethod() != null || !getInterceptorBindings().isEmpty() || hasStereotypeDeclarations(); } public Set<IInterceptorBinding> getInterceptorBindings() { Set<IInterceptorBinding> result = new HashSet<IInterceptorBinding>(); Set<IInterceptorBindingDeclaration> declarations = ClassBean.getInterceptorBindingDeclarations(this); for (IInterceptorBindingDeclaration declaration: declarations) { result.add(declaration.getInterceptorBinding()); } return result; } public boolean hasStereotypeDeclarations() { List<IAnnotationDeclaration> as = getAnnotations(); for (IAnnotationDeclaration a: as) { if(a instanceof IStereotypeDeclaration) { return true; } } return false; } public List<ParameterDefinition> getParameters() { return parameters; } public boolean isDisposer() { for (ParameterDefinition p: parameters) { if(p.isAnnotationPresent(CDIConstants.DISPOSES_ANNOTATION_TYPE_NAME)) return true; } return false; } public boolean isObserver() { for (ParameterDefinition p: parameters) { if(p.isAnnotationPresent(CDIConstants.OBSERVERS_ANNOTATION_TYPE_NAME)) return true; } return false; } public AnnotationDeclaration getPreDestroyMethod() { return annotationsByType.get(CDIConstants.PRE_DESTROY_TYPE_NAME); } public AnnotationDeclaration getPostConstructorMethod() { return annotationsByType.get(CDIConstants.POST_CONSTRUCTOR_TYPE_NAME); } static String[] getParams(String paramsString) { List<String> result = new ArrayList<String>(); int i = 0; int c1 = 0; int c2 = 0; char quote = '\0'; StringBuffer sb = new StringBuffer(); while(i < paramsString.length()) { char c = paramsString.charAt(i); if(c == ',' && c1 == 0 && c2 == 0 && quote == '\0') { if(sb.toString().trim().length() > 0) { result.add(sb.toString()); } sb.setLength(0); i++; continue; } else if(c == '(' && quote == '\0') { c1++; } else if(c == ')' && quote == '\0') { c1--; } else if(c == '<' && quote == '\0') { c2++; } else if(c == '>' && quote == '\0') { c2--; } else if((c == '\'' || c == '"') && quote == '\0') { quote = c; } else if(quote == c) { quote = '\0'; } sb.append(c); i++; } if(sb.length() > 0) { result.add(sb.toString()); } return result.toArray(new String[0]); } static String[] getParamTokens(String paramsString) { List<String> result = new ArrayList<String>(); int i = 0; int c1 = 0; int c2 = 0; char quote = '\0'; StringBuffer sb = new StringBuffer(); while(i < paramsString.length()) { char c = paramsString.charAt(i); boolean ws = Character.isWhitespace(c); if(ws && c1 == 0 && c2 == 0 && quote == '\0') { String t = sb.toString().trim(); if(t.length() > 0) { result.add(t); } sb.setLength(0); i++; continue; } else if(c == '(' && quote == '\0') { c1++; } else if(c == ')' && quote == '\0') { c1--; } else if(c == '<' && quote == '\0') { c2++; } else if(c == '>' && quote == '\0') { c2--; } else if((c == '\'' || c == '"') && quote == '\0') { quote = c; } else if(quote == c) { quote = '\0'; } sb.append(c); i++; } if(sb.length() > 0) { result.add(sb.toString()); } return result.toArray(new String[0]); } class CheckingValueInfo extends ValueInfo { IMethod m; CheckingValueInfo(IMethod m) { this.m = m; } void check() { ISourceRange r = null; try { r = m.getSourceRange(); } catch (JavaModelException e) { System.out.println("Method is obsolete: " + m); } if(r == null) { valueStartPosition = 0; valueLength = 0; } else { if(valueStartPosition + valueLength > r.getOffset() + r.getLength()) { System.out.println("Method is modified: " + m); valueStartPosition = 0; valueLength = 0; } } } public int getStartPosition() { check(); return valueStartPosition; } public int getLength() { check(); return valueLength; } } }
true
true
void loadParamDefinitions(IType contextType, IRootDefinitionContext context) throws CoreException { if(method == null) return; boolean parametersAreInjectionPoints = parametersAreInjectionPoints(); String[] parameterNames = method.getParameterNames(); if(parameterNames == null || parameterNames.length == 0) return; if(contextType == null || contextType.isBinary()) return; String content = typeDefinition.getContent(); if(content == null) return; ISourceRange range = method.getSourceRange(); ISourceRange nameRange = method.getNameRange(); if(nameRange != null) range = nameRange; int paramStart = content.indexOf('(', range.getOffset()); if(paramStart < 0) return; int declEnd = content.indexOf('{', paramStart); if(declEnd < 0) return; int paramEnd = content.lastIndexOf(')', declEnd); if(paramEnd < 0) return; String paramsString = content.substring(paramStart + 1, paramEnd); if(!parametersAreInjectionPoints && paramsString.indexOf("@Observes") >= 0) { parametersAreInjectionPoints = true; } if(!parametersAreInjectionPoints && paramsString.indexOf('@') < 0) return; String[] params = getParams(paramsString); String[] ps = method.getParameterTypes(); int start = paramStart + 1; for (int i = 0; i < params.length; i++) { if(ps.length <= i) { // CDICorePlugin.getDefault().logError(new IllegalArgumentException("Cannot parse method parameters for " + paramsString)); // The source code may be broken. Just ignore such errors. break; } if(!parametersAreInjectionPoints && params[i].indexOf('@') < 0) { start += params[i].length() + 1; continue; //do not need parameters without annotation } ParameterDefinition pd = new ParameterDefinition(); ParametedType type = context.getProject().getTypeFactory().getParametedType(method, ps[i]); pd.methodDefinition = this; pd.name = parameterNames[i]; pd.index = i; pd.type = type; String p = params[i].trim(); int pi = params[i].indexOf(p); ValueInfo v = new CheckingValueInfo(method); v.setValue(params[i]); v.valueStartPosition = start + pi; v.valueLength = p.length(); pd.setPosition(v); String[] tokens = getParamTokens(p); for (String q: tokens) { if(!q.startsWith("@")) continue; v = new CheckingValueInfo(method); v.setValue(q); v.valueStartPosition = start + params[i].indexOf(q); v.valueLength = q.length(); int s = q.indexOf('('); if(s >= 0) q = q.substring(0, s).trim(); String annotationType = EclipseJavaUtil.resolveType(contextType, q.substring(1).trim()); if(annotationType != null) pd.annotationsByTypeName.put(annotationType, v); } parameters.add(pd); start += params[i].length() + 1; } }
void loadParamDefinitions(IType contextType, IRootDefinitionContext context) throws CoreException { if(method == null) return; boolean parametersAreInjectionPoints = parametersAreInjectionPoints(); String[] parameterNames = method.getParameterNames(); if(parameterNames == null || parameterNames.length == 0) return; if(contextType == null || contextType.isBinary()) return; String content = typeDefinition.getContent(); if(content == null) return; ISourceRange range = method.getSourceRange(); ISourceRange nameRange = method.getNameRange(); if(nameRange != null) range = nameRange; int paramStart = content.indexOf('(', range.getOffset()); if(paramStart < 0) return; int declEnd = content.indexOf('{', paramStart); if(declEnd < 0) return; int paramEnd = content.lastIndexOf(')', declEnd); if(paramEnd < paramStart) paramEnd = declEnd; String paramsString = content.substring(paramStart + 1, paramEnd); if(!parametersAreInjectionPoints && paramsString.indexOf("@Observes") >= 0) { parametersAreInjectionPoints = true; } if(!parametersAreInjectionPoints && paramsString.indexOf('@') < 0) return; String[] params = getParams(paramsString); String[] ps = method.getParameterTypes(); int start = paramStart + 1; for (int i = 0; i < params.length; i++) { if(ps.length <= i) { // CDICorePlugin.getDefault().logError(new IllegalArgumentException("Cannot parse method parameters for " + paramsString)); // The source code may be broken. Just ignore such errors. break; } if(!parametersAreInjectionPoints && params[i].indexOf('@') < 0) { start += params[i].length() + 1; continue; //do not need parameters without annotation } ParameterDefinition pd = new ParameterDefinition(); ParametedType type = context.getProject().getTypeFactory().getParametedType(method, ps[i]); pd.methodDefinition = this; pd.name = parameterNames[i]; pd.index = i; pd.type = type; String p = params[i].trim(); int pi = params[i].indexOf(p); ValueInfo v = new CheckingValueInfo(method); v.setValue(params[i]); v.valueStartPosition = start + pi; v.valueLength = p.length(); pd.setPosition(v); String[] tokens = getParamTokens(p); for (String q: tokens) { if(!q.startsWith("@")) continue; v = new CheckingValueInfo(method); v.setValue(q); v.valueStartPosition = start + params[i].indexOf(q); v.valueLength = q.length(); int s = q.indexOf('('); if(s >= 0) q = q.substring(0, s).trim(); String annotationType = EclipseJavaUtil.resolveType(contextType, q.substring(1).trim()); if(annotationType != null) pd.annotationsByTypeName.put(annotationType, v); } parameters.add(pd); start += params[i].length() + 1; } }