code
stringlengths
73
34.1k
label
stringclasses
1 value
public ListSessionsResponse listSessions(ListSessionsRequest request) { checkNotNull(request, "The parameter request should NOT be null."); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_SESSION); if (request.getStatus() != null) { checkStringNotEmpty(request.getStatus(), "The parameter status should NOT be empty string."); internalRequest.addParameter(STATUS, request.getStatus()); } return invokeHttpClient(internalRequest, ListSessionsResponse.class); }
java
public ListAppResponse listApp(ListAppRequest request) { checkNotNull(request, "The parameter request should NOT be null."); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_APP); return invokeHttpClient(internalRequest, ListAppResponse.class); }
java
public ListAppStreamsResponse listAppStreams(String app) { ListAppStreamsRequest request = new ListAppStreamsRequest(); request.setApp(app); return listAppStreams(request); }
java
public StartRecordingResponse startRecording(String sessionId, String recording) { checkStringNotEmpty(sessionId, "The parameter sessionId should NOT be null or empty string."); checkStringNotEmpty(recording, "The parameter recording should NOT be null or empty string."); StartRecordingRequest request = new StartRecordingRequest().withSessionId(sessionId); InternalRequest internalRequest = createRequest(HttpMethodName.PUT, request, LIVE_SESSION, sessionId); internalRequest.addParameter(RECORDING, recording); return invokeHttpClient(internalRequest, StartRecordingResponse.class); }
java
public StopRecordingResponse stopRecording(String sessionId) { checkStringNotEmpty(sessionId, "The parameter sessionId should NOT be null or empty string."); StopRecordingRequest request = new StopRecordingRequest().withSessionId(sessionId); InternalRequest internalRequest = createRequest(HttpMethodName.PUT, request, LIVE_SESSION, sessionId); internalRequest.addParameter(RECORDING, null); return invokeHttpClient(internalRequest, StopRecordingResponse.class); }
java
public GetSessionSourceInfoResponse getSessionSourceInfo(String sessionId) { checkStringNotEmpty(sessionId, "The parameter sessionId should NOT be null or empty string."); GetSessionSourceInfoRequest request = new GetSessionSourceInfoRequest(); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_SESSION, sessionId); internalRequest.addParameter(SOURCE_INFO, null); return invokeHttpClient(internalRequest, GetSessionSourceInfoResponse.class); }
java
public GetRecordingResponse getRecording(String recording) { checkStringNotEmpty(recording, "The parameter recording should NOT be null or empty string."); GetRecordingRequest request = new GetRecordingRequest(); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, RECORDING, recording); return invokeHttpClient(internalRequest, GetRecordingResponse.class); }
java
public ListRecordingsResponse listRecordings() { GetRecordingRequest request = new GetRecordingRequest(); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, RECORDING); return invokeHttpClient(internalRequest, ListRecordingsResponse.class); }
java
public ListNotificationsResponse listNotifications() { ListNotificationsRequest request = new ListNotificationsRequest(); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_NOTIFICATION); return invokeHttpClient(internalRequest, ListNotificationsResponse.class); }
java
public CreateNotificationResponse createNotification(CreateNotificationRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getName(), "The parameter name should NOT be null or empty string."); checkStringNotEmpty(request.getEndpoint(), "The parameter endpoint should NOT be null or empty string."); InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, LIVE_NOTIFICATION); return invokeHttpClient(internalRequest, CreateNotificationResponse.class); }
java
public ListSecurityPoliciesResponse listSecurityPolicies() { ListSecurityPoliciesRequest request = new ListSecurityPoliciesRequest(); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_SECURITY_POLICY); return invokeHttpClient(internalRequest, ListSecurityPoliciesResponse.class); }
java
public ListDomainAppResponse listDomainApp(ListDomainAppRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getPlayDomain(), "playDomain should NOT be empty."); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_DOMAIN, request.getPlayDomain(), LIVE_APP); return invokeHttpClient(internalRequest, ListDomainAppResponse.class); }
java
public void updateStreamPresets(UpdateStreamPresetsRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getDomain(), "Domain should NOT be empty."); checkStringNotEmpty(request.getApp(), "App should NOT be empty"); checkStringNotEmpty(request.getStream(), "Stream should NOT be empty."); // presets can be null for letting stream to use domain's presets, // so no need to check if presets is null InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, LIVE_DOMAIN, request.getDomain(), LIVE_APP, request.getApp(), LIVE_STREAM, request.getStream()); internalRequest.addParameter("presets", null); invokeHttpClient(internalRequest, AbstractBceResponse.class); }
java
public void updateStreamPresets(String domain, String app, String stream, Map<String, String> presets) { UpdateStreamPresetsRequest request = new UpdateStreamPresetsRequest() .withDomain(domain) .withApp(app) .withStream(stream) .withPresets(presets); updateStreamPresets(request); }
java
public void updateStreamRecording(UpdateStreamRecordingRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getDomain(), "Domain should NOT be empty."); checkStringNotEmpty(request.getApp(), "App should NOT be empty"); checkStringNotEmpty(request.getStream(), "Stream should NOT be empty."); // recording can be null for letting stream to use domain's recording, // so no need to check if recording is null InternalRequest internalRequest = createRequest(HttpMethodName.PUT, request, LIVE_DOMAIN, request.getDomain(), LIVE_APP, request.getApp(), LIVE_STREAM, request.getStream()); internalRequest.addParameter("recording", request.getRecording()); invokeHttpClient(internalRequest, AbstractBceResponse.class); }
java
public void updateStreamRecording(String domain, String app, String stream, String recording) { UpdateStreamRecordingRequest request = new UpdateStreamRecordingRequest() .withDomain(domain) .withApp(app) .withStream(stream) .withRecording(recording); updateStreamRecording(request); }
java
public void updateStreamPullUrl(UpdateStreamPullUrlRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getDomain(), "Domain should NOT be empty."); checkStringNotEmpty(request.getApp(), "App should NOT be empty"); checkStringNotEmpty(request.getStream(), "Stream should NOT be empty."); checkStringNotEmpty(request.getPullUrl(), "PullUrl should NOT be empty."); InternalRequest internalRequest = createRequest(HttpMethodName.PUT, request, LIVE_DOMAIN, request.getDomain(), LIVE_APP, request.getApp(), LIVE_STREAM, request.getStream()); internalRequest.addParameter("pullUrl", request.getPullUrl()); invokeHttpClient(internalRequest, AbstractBceResponse.class); }
java
public void updateStreamPullUrl(String domain, String app, String stream, String pullUrl) { UpdateStreamPullUrlRequest request = new UpdateStreamPullUrlRequest() .withDomain(domain) .withApp(app) .withStream(stream) .withPullUrl(pullUrl); updateStreamPullUrl(request); }
java
public void updateStreamDestinationPushUrl(UpdateStreamDestinationPushUrlRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getDomain(), "Domain should NOT be empty."); checkStringNotEmpty(request.getApp(), "App should NOT be empty"); checkStringNotEmpty(request.getStream(), "Stream should NOT be empty."); InternalRequest internalRequest = createRequest(HttpMethodName.PUT, request, LIVE_DOMAIN, request.getDomain(), LIVE_APP, request.getApp(), LIVE_STREAM, request.getStream()); internalRequest.addParameter("destinationPushUrl", request.getDestinationPushUrl()); invokeHttpClient(internalRequest, AbstractBceResponse.class); }
java
public GetDomainStatisticsResponse getDomainStatistics(GetDomainStatisticsRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getDomain(), "Domain should NOT be empty."); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, STATISTICS, LIVE_DOMAIN, request.getDomain()); if (request.getStartDate() != null) { internalRequest.addParameter("startDate", request.getStartDate()); } if (request.getEndDate() != null) { internalRequest.addParameter("endDate", request.getEndDate()); } if (request.getAggregate() != null) { internalRequest.addParameter("aggregate", request.getAggregate().toString()); } return invokeHttpClient(internalRequest, GetDomainStatisticsResponse.class); }
java
public GetDomainStatisticsResponse getDomainStatistics(String domain) { GetDomainStatisticsRequest request = new GetDomainStatisticsRequest(); request.setDomain(domain); return getDomainStatistics(request); }
java
public GetAllDomainsPlayCountResponse getAllDomainsPlayCount(GetAllDomainsStatisticsRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getTimeInterval(), "timeInterval should NOT be null"); checkStringNotEmpty(request.getStartTime(), "startTime should NOT be null"); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, STATISTICS, LIVE_DOMAIN, "playcount"); internalRequest.addParameter("timeInterval", request.getTimeInterval()); internalRequest.addParameter("startTime", request.getStartTime()); if (request.getEndTime() != null) { internalRequest.addParameter("endTime", request.getEndTime()); } return invokeHttpClient(internalRequest, GetAllDomainsPlayCountResponse.class); }
java
public GetOneDomainPlayCountResponse getOneDomainPlayCount(GetOneDomainStatisticsRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkNotNull(request.getDomain(), "The domain parameter can not be null"); checkStringNotEmpty(request.getTimeInterval(), "timeInterval should NOT be null"); checkStringNotEmpty(request.getStartTime(), "startTime should NOT be null"); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, STATISTICS, LIVE_DOMAIN, request.getDomain(), "playcount"); internalRequest.addParameter("timeInterval", request.getTimeInterval()); internalRequest.addParameter("startTime", request.getStartTime()); if (request.getEndTime() != null) { internalRequest.addParameter("endTime", request.getEndTime()); } return invokeHttpClient(internalRequest, GetOneDomainPlayCountResponse.class); }
java
public ListDomainStatisticsResponse listDomainStatistics(ListDomainStatisticsRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getStartTime(), "startTime should NOT be empty"); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, STATISTICS, LIVE_DOMAIN, "list"); internalRequest.addParameter("startTime", request.getStartTime()); if (request.getEndTime() != null) { internalRequest.addParameter("endTime", request.getEndTime()); } if (request.getKeyword() != null) { internalRequest.addParameter("keyword", request.getKeyword()); } if (request.getKeywordType() != null) { internalRequest.addParameter("keywordType", request.getKeywordType()); } if (request.getOrderBy() != null) { internalRequest.addParameter("orderBy", request.getOrderBy()); } return invokeHttpClient(internalRequest, ListDomainStatisticsResponse.class); }
java
public ListStreamStatisticsResponse listStreamStatistics(ListStreamStatisticsRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getDomain(), "Domain should NOT be null"); checkStringNotEmpty(request.getApp(), "App should NOT be null"); checkStringNotEmpty(request.getStartTime(), "StartTime should NOT be null"); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, STATISTICS, LIVE_DOMAIN, request.getDomain(), LIVE_STREAM); internalRequest.addParameter("app", request.getApp()); internalRequest.addParameter("startTime", request.getStartTime()); if (request.getEndTime() != null) { internalRequest.addParameter("endTime", request.getEndTime()); } if (request.getKeyword() != null) { internalRequest.addParameter("keyword", request.getKeyword()); } if (request.getKeywordType() != null) { internalRequest.addParameter("keywordType", request.getKeywordType()); } if (request.getOrderBy() != null) { internalRequest.addParameter("orderBy", request.getOrderBy()); } if (request.getPageNo() != null) { internalRequest.addParameter("pageNo", request.getPageNo().toString()); } if (request.getPageSize() != null) { internalRequest.addParameter("pageSize", request.getPageSize().toString()); } return invokeHttpClient(internalRequest, ListStreamStatisticsResponse.class); }
java
public GetStreamStatisticsResponse getStreamStatistics(GetStreamStatisticsRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getDomain(), "Domain should NOT be null"); checkStringNotEmpty(request.getApp(), "App should NOT be null"); checkStringNotEmpty(request.getStream(), "Stream should NOT be null"); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, STATISTICS, LIVE_DOMAIN, request.getDomain(), LIVE_APP, request.getApp(), LIVE_STREAM, request.getStream()); if (request.getStartDate() != null) { internalRequest.addParameter("startDate", request.getStartDate()); } if (request.getEndDate() != null) { internalRequest.addParameter("endDate", request.getEndDate()); } if (request.getAggregate() != null) { internalRequest.addParameter("aggregate", request.getAggregate().toString()); } return invokeHttpClient(internalRequest, GetStreamStatisticsResponse.class); }
java
public CreateVpcResponse createVpc(String name, String cidr) { CreateVpcRequest request = new CreateVpcRequest(); request.withName(name).withCidr(cidr); return createVpc(request); }
java
public ListVpcsResponse listVpcs(ListVpcsRequest request) { checkNotNull(request, "request should not be null."); InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, VPC_PREFIX); if (request.getMarker() != null) { internalRequest.addParameter("marker", request.getMarker()); } if (request.getMaxKeys() > 0) { internalRequest.addParameter("maxKeys", String.valueOf(request.getMaxKeys())); } if (request.getIsDefault() != null) { internalRequest.addParameter("isDefault", request.getIsDefault().toString()); } return invokeHttpClient(internalRequest, ListVpcsResponse.class); }
java
public GetVpcResponse getVpc(GetVpcRequest getVpcRequest) { checkNotNull(getVpcRequest, "request should not be null."); checkNotNull(getVpcRequest.getVpcId(), "request vpcId should not be null."); InternalRequest internalRequest = this.createRequest( getVpcRequest, HttpMethodName.GET, VPC_PREFIX, getVpcRequest.getVpcId()); return this.invokeHttpClient(internalRequest, GetVpcResponse.class); }
java
public void modifyInstanceAttributes(String name, String vpcId) { ModifyVpcAttributesRequest request = new ModifyVpcAttributesRequest(); modifyInstanceAttributes(request.withName(name).withVpcId(vpcId)); }
java
public GetClusterResponse getCluster(GetClusterRequest request) { checkNotNull(request, "request should not be null."); checkStringNotEmpty(request.getClusterId(), "The parameter clusterId should not be null or empty string."); InternalRequest internalRequest = this.createRequest( request, HttpMethodName.GET, CLUSTER, request.getClusterId()); return this.invokeHttpClient(internalRequest, GetClusterResponse.class); }
java
public void modifyInstanceGroups(ModifyInstanceGroupsRequest request) { checkNotNull(request, "request should not be null."); checkStringNotEmpty(request.getClusterId(), "The clusterId should not be null or empty string."); checkNotNull(request.getInstanceGroups(), "The instanceGroups should not be null."); StringWriter writer = new StringWriter(); try { JsonGenerator jsonGenerator = JsonUtils.jsonGeneratorOf(writer); jsonGenerator.writeStartObject(); jsonGenerator.writeArrayFieldStart("instanceGroups"); for (ModifyInstanceGroupConfig instanceGroup : request.getInstanceGroups()) { checkStringNotEmpty(instanceGroup.getId(), "The instanceGroupId should not be null or empty string."); jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("id", instanceGroup.getId()); jsonGenerator.writeNumberField("instanceCount", instanceGroup.getInstanceCount()); jsonGenerator.writeEndObject(); } jsonGenerator.writeEndArray(); jsonGenerator.writeEndObject(); jsonGenerator.close(); } catch (IOException e) { throw new BceClientException("Fail to generate json", e); } byte[] json = null; try { json = writer.toString().getBytes(DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { throw new BceClientException("Fail to get UTF-8 bytes", e); } InternalRequest internalRequest = this.createRequest(request, HttpMethodName.PUT, CLUSTER, request.getClusterId(), INSTANCE_GROUP); internalRequest.addHeader(Headers.CONTENT_LENGTH, String.valueOf(json.length)); internalRequest.addHeader(Headers.CONTENT_TYPE, "application/json"); internalRequest.setContent(RestartableInputStream.wrap(json)); if (request.getClientToken() != null) { internalRequest.addParameter("clientToken", request.getClientToken()); } this.invokeHttpClient(internalRequest, AbstractBceResponse.class); }
java
public void terminateCluster(TerminateClusterRequest request) { checkNotNull(request, "request should not be null."); checkStringNotEmpty(request.getClusterId(), "The parameter clusterId should not be null or empty string."); InternalRequest internalRequest = this.createRequest( request, HttpMethodName.DELETE, CLUSTER, request.getClusterId()); this.invokeHttpClient(internalRequest, AbstractBceResponse.class); }
java
public ListInstanceGroupsResponse listInstanceGroups(ListInstanceGroupsRequest request) { checkNotNull(request, "request should not be null."); checkStringNotEmpty(request.getClusterId(), "The parameter clusterId should not be null or empty string."); InternalRequest internalRequest = this.createRequest( request, HttpMethodName.GET, CLUSTER, request.getClusterId(), INSTANCE_GROUP); return this.invokeHttpClient(internalRequest, ListInstanceGroupsResponse.class); }
java
public ListInstancesResponse listInstances(ListInstancesRequest request) { checkNotNull(request, "request should not be null."); checkStringNotEmpty(request.getClusterId(), "The parameter clusterId should not be null or empty string."); checkStringNotEmpty(request.getInstanceGroupId(), "The parameter instanceGroupId should not be null or empty string."); InternalRequest internalRequest = this.createRequest( request, HttpMethodName.GET, CLUSTER, request.getClusterId(), INSTANCE_GROUP, request.getInstanceGroupId(), INSTANCE); return this.invokeHttpClient(internalRequest, ListInstancesResponse.class); }
java
public ListInstancesResponse listInstances(String clusterId, String instanceGroupId) { return listInstances(new ListInstancesRequest().withClusterId(clusterId).withInstanceGroupId(instanceGroupId)); }
java
public AddStepsResponse addSteps(AddStepsRequest request) { checkNotNull(request, "request should not be null."); checkNotNull(request.getSteps(), "The parameter steps should not be null."); checkStringNotEmpty(request.getClusterId(), "The parameter clusterId should not be null or empty string."); StringWriter writer = new StringWriter(); List<StepConfig> steps = request.getSteps(); try { JsonGenerator jsonGenerator = JsonUtils.jsonGeneratorOf(writer); jsonGenerator.writeStartObject(); jsonGenerator.writeArrayFieldStart("steps"); for (StepConfig step : steps) { jsonGenerator.writeStartObject(); if (step.getName() != null) { jsonGenerator.writeStringField("name", step.getName()); } jsonGenerator.writeStringField("type", step.getType()); jsonGenerator.writeStringField("actionOnFailure", step.getActionOnFailure()); jsonGenerator.writeObjectFieldStart("properties"); for (String propertyKey : step.getProperties().keySet()) { jsonGenerator.writeObjectField(propertyKey, step.getProperties().get(propertyKey)); } jsonGenerator.writeEndObject(); jsonGenerator.writeArrayFieldStart("additionalFiles"); for (AdditionalFile additionalFile : step.getAdditionalFiles()) { jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("remote", additionalFile.getRemote()); jsonGenerator.writeStringField("local", additionalFile.getLocal()); jsonGenerator.writeEndObject(); } jsonGenerator.writeEndArray(); jsonGenerator.writeEndObject(); } jsonGenerator.writeEndArray(); jsonGenerator.writeEndObject(); jsonGenerator.close(); } catch (IOException e) { throw new BceClientException("Fail to generate json", e); } byte[] json = null; try { json = writer.toString().getBytes(DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { throw new BceClientException("Fail to get UTF-8 bytes", e); } InternalRequest internalRequest = this.createRequest( request, HttpMethodName.POST, CLUSTER, request.getClusterId(), STEP); internalRequest.addHeader(Headers.CONTENT_LENGTH, String.valueOf(json.length)); internalRequest.addHeader(Headers.CONTENT_TYPE, "application/json"); internalRequest.setContent(RestartableInputStream.wrap(json)); if (request.getClientToken() != null) { internalRequest.addParameter("clientToken", request.getClientToken()); } return this.invokeHttpClient(internalRequest, AddStepsResponse.class); }
java
public GetDocumentImagesResponse getDocumentImages(String documentId) { checkNotNull(documentId, "documentId should not be null."); GetDocumentImagesRequest request = new GetDocumentImagesRequest(); request.setDocumentId(documentId); InternalRequest internalRequest = this.createRequest(HttpMethodName.GET, request, DOC, request.getDocumentId()); internalRequest.addParameter("getImages", null); GetDocumentImagesResponse response; try { response = this.invokeHttpClient(internalRequest, GetDocumentImagesResponse.class); } finally { try { internalRequest.getContent().close(); } catch (Exception e) { // ignore exception } } return response; }
java
public ListDocumentsResponse listDocuments() { ListDocumentsRequest request = new ListDocumentsRequest(); InternalRequest internalRequest = this.createRequest(HttpMethodName.GET, request, DOC); ListDocumentsResponse response; try { response = this.invokeHttpClient(internalRequest, ListDocumentsResponse.class); } finally { try { internalRequest.getContent().close(); } catch (Exception e) { // ignore exception } } return response; }
java
public GetDocumentDownloadResponse getDocumentDownload(String documentId) { checkNotNull(documentId, "documentId should not be null."); GetDocumentDownloadRequest request = new GetDocumentDownloadRequest(); request.setDocumentId(documentId); InternalRequest internalRequest = this.createRequest(HttpMethodName.GET, request, DOC, request.getDocumentId()); internalRequest.addParameter("download", null); GetDocumentDownloadResponse response; try { response = this.invokeHttpClient(internalRequest, GetDocumentDownloadResponse.class); } finally { try { internalRequest.getContent().close(); } catch (Exception e) { // ignore exception } } return response; }
java
public void setMode(String mode) { checkNotNull(mode, "mode should not be null"); if (MODE_ASYNC.equals(mode) || MODE_SYNC.equals(mode)) { this.mode = mode; } else { throw new IllegalArgumentException("illegal mode: " + mode); } }
java
public AddStepsRequest withStep(StepConfig step) { if (this.steps == null) { this.steps = new ArrayList<StepConfig>(); } this.steps.add(step); return this; }
java
public static String generateHostHeader(URI uri) { String host = uri.getHost(); if (isUsingNonDefaultPort(uri)) { host += ":" + uri.getPort(); } return host; }
java
public Key withAttribute(String attributeName, AttributeValue value) { if (this.attributes == null) { this.attributes = new HashMap<String, AttributeValue>(); } attributes.put(attributeName, value); return this; }
java
private void initEngine() { engine = (NashornScriptEngine) new ScriptEngineManager().getEngineByName("nashorn"); try { engine.eval("(function(global){global.global = global})(this);"); engine.eval(NashornVueTemplateCompiler.NASHORN_VUE_TEMPLATE_COMPILER); } catch (ScriptException e) { e.printStackTrace(); } }
java
public VueTemplateCompilerResult compile(String htmlTemplate) throws VueTemplateCompilerException { ScriptObjectMirror templateCompilerResult; try { templateCompilerResult = (ScriptObjectMirror) engine.invokeFunction("compile", htmlTemplate); } catch (ScriptException | NoSuchMethodException e) { e.printStackTrace(); throw new VueTemplateCompilerException( "An error occurred while compiling the template: " + htmlTemplate + " -> " + e.getMessage()); } String renderFunction = (String) templateCompilerResult.get("render"); String[] staticRenderFunctions = ((ScriptObjectMirror) templateCompilerResult.get("staticRenderFns")).to(String[].class); return new VueTemplateCompilerResult(renderFunction, staticRenderFunctions); }
java
public static boolean isMethodVisibleInTemplate(ExecutableElement method) { return isMethodVisibleInJS(method) && !hasAnnotation(method, Computed.class) && !hasAnnotation(method, Watch.class) && !hasAnnotation(method, PropValidator.class) && !hasAnnotation(method, PropDefault.class) && !method.getModifiers().contains(Modifier.STATIC) && !method.getModifiers().contains(Modifier.PRIVATE); }
java
public static int getSuperComponentCount(TypeElement component) { return getSuperComponentType(component) .map(superComponent -> getSuperComponentCount(superComponent) + 1) .orElse(0); }
java
public static boolean hasTemplate(ProcessingEnvironment processingEnvironment, TypeElement component) { Component annotation = component.getAnnotation(Component.class); if (annotation == null || !annotation.hasTemplate()) { return false; } if (component.getModifiers().contains(Modifier.ABSTRACT)) { return false; } return !hasInterface(processingEnvironment, component.asType(), HasRender.class); }
java
private void compileTemplateString(ComponentExposedTypeGenerator exposedTypeGenerator, TemplateParserResult templateParserResult) { VueTemplateCompilerResult compilerResult; try { VueTemplateCompiler vueTemplateCompiler = new VueTemplateCompiler(); compilerResult = vueTemplateCompiler.compile(templateParserResult.getProcessedTemplate()); } catch (VueTemplateCompilerException e) { e.printStackTrace(); throw new RuntimeException(); } generateGetRenderFunction(exposedTypeGenerator, compilerResult, templateParserResult); generateGetStaticRenderFunctions(exposedTypeGenerator, compilerResult); }
java
private void generateGetRenderFunction(ComponentExposedTypeGenerator exposedTypeGenerator, VueTemplateCompilerResult result, TemplateParserResult templateParserResult) { MethodSpec.Builder getRenderFunctionBuilder = MethodSpec .methodBuilder("getRenderFunction") .addModifiers(Modifier.PRIVATE) .returns(Function.class) .addStatement("String renderFunctionString = $S", result.getRenderFunction()); for (VariableInfo vModelField : templateParserResult.getvModelDataFields()) { String placeHolderVModelValue = vModelFieldToPlaceHolderField(vModelField.getName()); String fieldName = vModelField.getName(); if (vModelField instanceof ComputedVariableInfo) fieldName = ((ComputedVariableInfo) vModelField).getFieldName(); getRenderFunctionBuilder .addStatement( "renderFunctionString = $T.replaceVariableInRenderFunction(renderFunctionString, $S, this, () -> this.$L = $L)", VueGWTTools.class, placeHolderVModelValue, fieldName, getFieldMarkingValueForType(vModelField.getType()) ); } getRenderFunctionBuilder .addStatement("return new $T(renderFunctionString)", Function.class); exposedTypeGenerator.getClassBuilder().addMethod(getRenderFunctionBuilder.build()); }
java
private void generateGetStaticRenderFunctions(ComponentExposedTypeGenerator exposedTypeGenerator, VueTemplateCompilerResult result) { CodeBlock.Builder staticFunctions = CodeBlock.builder(); boolean isFirst = true; for (String staticRenderFunction : result.getStaticRenderFunctions()) { if (!isFirst) { staticFunctions.add(", "); } else { isFirst = false; } staticFunctions.add("new $T($S)", Function.class, staticRenderFunction); } MethodSpec.Builder getStaticRenderFunctionsBuilder = MethodSpec .methodBuilder("getStaticRenderFunctions") .addModifiers(Modifier.PRIVATE) .returns(Function[].class) .addStatement("return new $T[] { $L }", Function.class, staticFunctions.build()); exposedTypeGenerator.getClassBuilder().addMethod(getStaticRenderFunctionsBuilder.build()); }
java
private void processTemplateExpressions(ComponentExposedTypeGenerator exposedTypeGenerator, TemplateParserResult templateParserResult) { for (TemplateExpression expression : templateParserResult.getExpressions()) { generateTemplateExpressionMethod(exposedTypeGenerator, expression, templateParserResult.getTemplateName()); } // Declare methods in the component String templateMethods = templateParserResult.getExpressions() .stream() .map(expression -> "p." + expression.getId()) .collect(Collectors.joining(", ")); exposedTypeGenerator.getOptionsBuilder() .addStatement("options.registerTemplateMethods($L)", templateMethods); }
java
private void generateTemplateExpressionMethod(ComponentExposedTypeGenerator exposedTypeGenerator, TemplateExpression expression, String templateName) { MethodSpec.Builder templateExpressionMethodBuilder = MethodSpec .methodBuilder(expression.getId()) .addModifiers(Modifier.PUBLIC) .addAnnotation(JsMethod.class) .addAnnotation(getUnusableByJSAnnotation()) .returns(expression.getType()); String expressionPosition = templateName; if (expression.getLineInHtml() != null) { expressionPosition += ", line " + expression.getLineInHtml(); } templateExpressionMethodBuilder.addComment(expressionPosition); expression .getParameters() .forEach(parameter -> templateExpressionMethodBuilder.addParameter(parameter.getType(), parameter.getName())); if (expression.isReturnString()) { templateExpressionMethodBuilder.addStatement("return $T.templateExpressionToString($L)", VueGWTTools.class, expression.getBody()); } else if (expression.isReturnVoid()) { templateExpressionMethodBuilder.addStatement("$L", expression.getBody()); } else if (expression.isReturnAny()) { templateExpressionMethodBuilder.addStatement("return $T.asAny($L)", Js.class, expression.getBody()); } else if (expression.isShouldCast()) { templateExpressionMethodBuilder.addStatement("return ($T) ($L)", expression.getType(), expression.getBody()); } else { templateExpressionMethodBuilder.addStatement("return $L", expression.getBody()); } exposedTypeGenerator.getClassBuilder().addMethod(templateExpressionMethodBuilder.build()); exposedTypeGenerator.addMethodToProto(expression.getId()); }
java
public static String componentToTagName(Element componentElement) throws MissingComponentAnnotationException { Component componentAnnotation = componentElement.getAnnotation(Component.class); JsComponent jsComponentAnnotation = componentElement.getAnnotation(JsComponent.class); String annotationNameValue; if (componentAnnotation != null) { annotationNameValue = componentAnnotation.name(); } else if (jsComponentAnnotation != null) { annotationNameValue = jsComponentAnnotation.value(); } else { throw new MissingComponentAnnotationException(); } if (!"".equals(annotationNameValue)) { return annotationNameValue; } // Drop "Component" at the end of the class name String componentClassName = componentElement .getSimpleName() .toString() .replaceAll("Component$", ""); // Convert from CamelCase to kebab-case return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, componentClassName).toLowerCase(); }
java
public static String directiveToTagName(String directiveClassName) { // Drop "Component" at the end of the class name directiveClassName = directiveClassName.replaceAll("Directive$", ""); // Convert from CamelCase to kebab-case return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, directiveClassName).toLowerCase(); }
java
private void initLoopVariable(String type, String name, TemplateParserContext context) { this.loopVariableInfo = context.addLocalVariable(context.getFullyQualifiedNameForClassName(type.trim()), name.trim()); }
java
private void initIndexVariable(String name, TemplateParserContext context) { this.indexVariableInfo = context.addLocalVariable("int", name.trim()); }
java
private void initKeyVariable(String name, TemplateParserContext context) { this.keyVariableInfo = context.addLocalVariable("String", name.trim()); }
java
public String toTemplateString() { String[] parametersName = this.parameters.stream().map(VariableInfo::getName).toArray(String[]::new); return this.getId() + "(" + String.join(", ", parametersName) + ")"; }
java
public TemplateParserResult parseHtmlTemplate(String htmlTemplate, TemplateParserContext context, Elements elements, Messager messager, URI htmlTemplateUri) { this.context = context; this.elements = elements; this.messager = messager; this.logger = new TemplateParserLogger(context, messager); this.htmlTemplateUri = htmlTemplateUri; initJerichoConfig(this.logger); Source source = new Source(htmlTemplate); outputDocument = new OutputDocument(source); result = new TemplateParserResult(context); processImports(source); result.setScopedCss(processScopedCss(source)); source.getChildElements().forEach(this::processElement); result.setProcessedTemplate(outputDocument.toString()); return result; }
java
private void processImports(Source doc) { doc .getAllElements() .stream() .filter(element -> "vue-gwt:import".equalsIgnoreCase(element.getName())) .peek(importElement -> { String classAttributeValue = importElement.getAttributeValue("class"); if (classAttributeValue != null) { context.addImport(classAttributeValue); } String staticAttributeValue = importElement.getAttributeValue("static"); if (staticAttributeValue != null) { context.addStaticImport(staticAttributeValue); } }) .forEach(outputDocument::remove); }
java
private void processElement(Element element) { context.setCurrentSegment(element); currentProp = null; currentAttribute = null; // Process attributes boolean shouldPopContext = processElementAttributes(element); // Process text segments StreamSupport .stream(((Iterable<Segment>) element::getNodeIterator).spliterator(), false) .filter(segment -> !(segment instanceof Tag) && !(segment instanceof CharacterReference)) .filter(segment -> { for (Element child : element.getChildElements()) { if (child.encloses(segment)) { return false; } } return true; }) .forEach(this::processTextNode); // Recurse downwards element.getChildElements(). forEach(this::processElement); // After downward recursion, pop the context layer if necessary if (shouldPopContext) { context.popContextLayer(); } }
java
private TypeMirror getTypeFromDOMElement(Element element) { return DOMElementsUtil .getTypeForElementTag(element.getStartTag().getName()) .map(Class::getCanonicalName) .map(elements::getTypeElement) .map(TypeElement::asType) .orElse(null); }
java
private void registerMandatoryAttributes(Attributes attributes) { // see https://sourceforge.net/p/jerichohtml/discussion/350024/thread/501a7d05/ Map<String, String> attrs = context.getMandatoryAttributes(); if (!attrs.isEmpty()) { for (Entry<String, String> i : attrs.entrySet()) { String v = i.getValue(); if (v == null) { outputDocument.insert(attributes.getBegin(), " " + i.getKey() + " "); } else { outputDocument.insert(attributes.getBegin(), " " + i.getKey() + "\"" + v + "\" "); } } } }
java
private TypeName getExpressionReturnTypeForAttribute(Attribute attribute, Map<String, Class<?>> propertiesTypes) { String attributeName = attribute.getKey().toLowerCase(); if (attributeName.indexOf("@") == 0 || attributeName.indexOf("v-on:") == 0) { return TypeName.VOID; } if ("v-if".equals(attributeName) || "v-show".equals(attributeName)) { return TypeName.BOOLEAN; } if (isBoundedAttribute(attributeName)) { String unboundedAttributeName = boundedAttributeToAttributeName(attributeName); if (unboundedAttributeName.equals("class") || unboundedAttributeName.equals("style")) { return TypeName.get(Any.class); } if (propertiesTypes.containsKey(unboundedAttributeName)) { return TypeName.get(propertiesTypes.get(unboundedAttributeName)); } } if (currentProp != null) { return currentProp.getType(); } return TypeName.get(Any.class); }
java
private String processVForValue(String vForValue) { VForDefinition vForDef = new VForDefinition(vForValue, context, logger); // Set return of the "in" expression currentExpressionReturnType = vForDef.getInExpressionType(); String inExpression = this.processExpression(vForDef.getInExpression()); // And return the newly built definition return vForDef.getVariableDefinition() + " in " + inExpression; }
java
private String processSlotScopeValue(String value) { SlotScopeDefinition slotScopeDefinition = new SlotScopeDefinition(value, context, logger); return slotScopeDefinition.getSlotScopeVariableName(); }
java
private String processExpression(String expressionString) { expressionString = expressionString == null ? "" : expressionString.trim(); if (expressionString.isEmpty()) { if (isAttributeBinding(currentAttribute)) { logger.error( "Empty expression in template property binding. If you want to pass an empty string then simply don't use binding: my-attribute=\"\"", currentAttribute.toString()); } else if (isEventBinding(currentAttribute)) { logger.error("Empty expression in template event binding.", currentAttribute.toString()); } else { return ""; } } if (expressionString.startsWith("{")) { logger.error( "Object literal syntax are not supported yet in Vue GWT, please use map(e(\"key1\", myValue), e(\"key2\", myValue2 > 5)...) instead. The object returned by map() is a regular Javascript Object (JsObject) with the given key/values.", expressionString); } if (expressionString.startsWith("[")) { logger.error( "Array literal syntax are not supported yet in Vue GWT, please use array(myValue, myValue2 > 5...) instead. The object returned by array() is a regular Javascript Array (JsArray) with the given values.", expressionString); } if (shouldSkipExpressionProcessing(expressionString)) { return expressionString; } return processJavaExpression(expressionString).toTemplateString(); }
java
private boolean shouldSkipExpressionProcessing(String expressionString) { // We don't skip if it's a component prop as we want Java validation // We don't optimize String expression, as we want GWT to convert Java values // to String for us (Enums, wrapped primitives...) return currentProp == null && !String.class .getCanonicalName() .equals(currentExpressionReturnType.toString()) && isSimpleVueJsExpression( expressionString); }
java
private TemplateExpression processJavaExpression(String expressionString) { Expression expression; try { expression = JavaParser.parseExpression(expressionString); } catch (ParseProblemException parseException) { logger.error("Couldn't parse Expression, make sure it is valid Java.", expressionString); throw parseException; } resolveTypesUsingImports(expression); resolveStaticMethodsUsingImports(expression); checkMethodNames(expression); // Find the parameters used by the expression List<VariableInfo> expressionParameters = new LinkedList<>(); findExpressionParameters(expression, expressionParameters); // If there is a cast first, we use this as the type of our expression if (currentProp == null) { expression = getTypeFromCast(expression); } // Update the expression as it might have been changed expressionString = expression.toString(); // Add the resulting expression to our result return result.addExpression(expressionString, currentExpressionReturnType, currentProp == null, expressionParameters); }
java
private void resolveTypesUsingImports(Expression expression) { if (expression instanceof NodeWithType) { NodeWithType<?, ?> nodeWithType = ((NodeWithType<?, ?>) expression); nodeWithType.setType(getQualifiedName(nodeWithType.getType())); } // Recurse downward in the expression expression .getChildNodes() .stream() .filter(Expression.class::isInstance) .map(Expression.class::cast) .forEach(this::resolveTypesUsingImports); }
java
private void resolveStaticMethodsUsingImports(Expression expression) { if (expression instanceof MethodCallExpr) { MethodCallExpr methodCall = ((MethodCallExpr) expression); String methodName = methodCall.getName().getIdentifier(); if (!methodCall.getScope().isPresent() && context.hasStaticMethod(methodName)) { methodCall.setName(context.getFullyQualifiedNameForMethodName(methodName)); } } // Recurse downward in the expression expression .getChildNodes() .stream() .filter(Expression.class::isInstance) .map(Expression.class::cast) .forEach(this::resolveStaticMethodsUsingImports); }
java
private void checkMethodNames(Expression expression) { if (expression instanceof MethodCallExpr) { MethodCallExpr methodCall = ((MethodCallExpr) expression); if (!methodCall.getScope().isPresent()) { String methodName = methodCall.getName().getIdentifier(); if (!context.hasMethod(methodName) && !context.hasStaticMethod(methodName)) { logger.error("Couldn't find the method \"" + methodName + "\". " + "Make sure it is not private."); } } } for (com.github.javaparser.ast.Node node : expression.getChildNodes()) { if (!(node instanceof Expression)) { continue; } Expression childExpr = (Expression) node; checkMethodNames(childExpr); } }
java
private void createStaticGetMethod(TypeElement component, ClassName vueFactoryClassName, Builder vueFactoryBuilder, List<CodeBlock> staticInitParameters) { MethodSpec.Builder getBuilder = MethodSpec .methodBuilder("get") .addModifiers(Modifier.STATIC, Modifier.PUBLIC) .returns(vueFactoryClassName); getBuilder.beginControlFlow("if ($L == null)", INSTANCE_PROP); getBuilder.addStatement("$L = new $T()", INSTANCE_PROP, vueFactoryClassName); if (hasTemplate(processingEnv, component)) { getBuilder.addStatement("$L.injectComponentCss($T.getScopedCss())", INSTANCE_PROP, componentExposedTypeName(component)); } getBuilder.addCode("$L.init(", INSTANCE_PROP); boolean isFirst = true; for (CodeBlock staticInitParameter : staticInitParameters) { if (!isFirst) { getBuilder.addCode(", "); } getBuilder.addCode(staticInitParameter); isFirst = false; } getBuilder.addCode(");"); getBuilder.endControlFlow(); getBuilder.addStatement("return $L", INSTANCE_PROP); vueFactoryBuilder.addMethod(getBuilder.build()); }
java
public TemplateExpression addExpression(String expression, TypeName expressionType, boolean shouldCast, List<VariableInfo> parameters) { String id = "exp$" + this.expressions.size(); TemplateExpression templateExpression = new TemplateExpression(id, expression.trim(), expressionType, shouldCast, parameters, context.getCurrentLine().orElse(null)); this.expressions.add(templateExpression); return templateExpression; }
java
public void addRef(String name, TypeMirror elementType, boolean isArray) { refs.add(new RefInfo(name, elementType, isArray)); }
java
public static String escapeStringForJsRegexp(String input) { JsString string = uncheckedCast(input); return string.replace(ESCAPE_JS_STRING_REGEXP, "\\$&"); }
java
private void registerLocalDirectives(Component annotation, MethodSpec.Builder initBuilder) { try { Class<?>[] componentsClass = annotation.directives(); if (componentsClass.length > 0) { addGetDirectivesStatement(initBuilder); } Stream .of(componentsClass) .forEach(clazz -> initBuilder.addStatement("directives.set($S, new $T())", directiveToTagName(clazz.getName()), directiveOptionsName(clazz))); } catch (MirroredTypesException mte) { List<DeclaredType> classTypeMirrors = (List<DeclaredType>) mte.getTypeMirrors(); if (!classTypeMirrors.isEmpty()) { addGetDirectivesStatement(initBuilder); } classTypeMirrors.forEach(classTypeMirror -> { TypeElement classTypeElement = (TypeElement) classTypeMirror.asElement(); initBuilder.addStatement("directives.set($S, new $T())", directiveToTagName(classTypeElement.getSimpleName().toString()), directiveOptionsName(classTypeElement)); }); } }
java
@JsOverlay public final void initRenderFunctions(Function renderFunctionString, Function[] staticRenderFnsStrings) { this.setRender(renderFunctionString); this.setStaticRenderFns(cast(staticRenderFnsStrings)); }
java
@JsOverlay public final void initData(boolean useFactory, Set<String> fieldNames) { JsPropertyMap<Object> dataFields = JsPropertyMap.of(); dataFieldsToProxy = new HashSet<>(); for (String fieldName : fieldNames) { dataFields.set(fieldName, null); // If field name starts with $ or _ Vue.js won't proxify it so we must do it if (fieldName.startsWith("$") || fieldName.startsWith("_")) { dataFieldsToProxy.add(fieldName); } } if (useFactory) { String dataFieldsJSON = JSON.stringify(dataFields); this.setData((DataFactory) () -> JSON.parse(dataFieldsJSON)); } else { this.setData((DataFactory) () -> dataFields); } }
java
@JsOverlay public final void addJavaComputed(Function javaMethod, String computedPropertyName, ComputedKind kind) { ComputedOptions computedDefinition = getComputedOptions(computedPropertyName); if (computedDefinition == null) { computedDefinition = new ComputedOptions(); addComputedOptions(computedPropertyName, computedDefinition); } if (kind == ComputedKind.GETTER) { computedDefinition.get = javaMethod; } else if (kind == ComputedKind.SETTER) { computedDefinition.set = javaMethod; } }
java
@JsOverlay public final void addJavaWatch(Function javaMethod, String watchedPropertyName, boolean isDeep, boolean isImmediate) { if (!isDeep && !isImmediate) { addWatch(watchedPropertyName, javaMethod); return; } JsPropertyMap<Object> watchDefinition = JsPropertyMap.of(); watchDefinition.set("handler", javaMethod); watchDefinition.set("deep", isDeep); watchDefinition.set("immediate", isImmediate); addWatch(watchedPropertyName, watchDefinition); }
java
@JsOverlay public final void addJavaProp(String propName, String fieldName, boolean required, String exposedTypeName) { if (propsToProxy == null) { propsToProxy = new HashSet<>(); } PropOptions propDefinition = new PropOptions(); propDefinition.required = required; if (exposedTypeName != null) { propDefinition.type = ((JsPropertyMap<Object>) DomGlobal.window).get(exposedTypeName); } propsToProxy.add(new PropProxyDefinition(propName, fieldName)); addProp(propName, propDefinition); }
java
private void findLocalComponentsForComponent(LocalComponents localComponents, TypeElement componentTypeElement) { Component componentAnnotation = componentTypeElement.getAnnotation(Component.class); if (componentAnnotation == null) { return; } processLocalComponentClass(localComponents, componentTypeElement); getComponentLocalComponents(elements, componentTypeElement) .stream() .map(DeclaredType.class::cast) .map(DeclaredType::asElement) .map(TypeElement.class::cast) .forEach(childTypeElement -> processLocalComponentClass(localComponents, childTypeElement)); getSuperComponentType(componentTypeElement) .ifPresent(superComponentType -> findLocalComponentsForComponent( localComponents, superComponentType)); }
java
public void customizeVueObserverPrototype(VueObserver vueObserver) { vueObserveArrayFunction = vueObserver.getObserveArray(); vueWalkFunction = vueObserver.getWalk(); vueObserver.setWalk(toObserve -> { if (observeJavaObject(toObserve)) { return; } vueWalkFunction.call(this, toObserve); }); }
java
public static boolean hasInjectAnnotation(Element element) { for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) { String annotationQualifiedName = annotationMirror.getAnnotationType().toString(); if (annotationQualifiedName.equals(Inject.class.getCanonicalName())) { return true; } if (annotationQualifiedName.equals("com.google.inject.Inject")) { return true; } } return false; }
java
public void generate(TypeElement directiveTypeElement) { ClassName optionsClassName = GeneratorsNameUtil.directiveOptionsName(directiveTypeElement); Builder componentClassBuilder = TypeSpec .classBuilder(optionsClassName) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .superclass(VueDirectiveOptions.class) .addAnnotation(JsType.class) .addJavadoc("VueComponent Directive Options for directive {@link $S}", directiveTypeElement.getQualifiedName().toString()); // Initialize constructor MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC); // Add the Java Component Instance initialization constructorBuilder.addStatement("this.$L = new $T()", "vuegwt$javaDirectiveInstance", TypeName.get(directiveTypeElement.asType())); // Call the method to copy hooks functions constructorBuilder.addStatement("this.copyHooks()"); // Finish building the constructor componentClassBuilder.addMethod(constructorBuilder.build()); // Build the DirectiveOptions class GeneratorsUtil.toJavaFile(filer, componentClassBuilder, optionsClassName, directiveTypeElement); }
java
private void exposeExposedFieldsToJs() { if (fieldsWithNameExposed.isEmpty()) { return; } MethodSpec.Builder exposeFieldMethod = MethodSpec .methodBuilder("vg$ef") .addAnnotation(JsMethod.class); fieldsWithNameExposed .forEach(field -> exposeFieldMethod .addStatement("this.$L = $T.v()", field.getName(), FieldsExposer.class) ); exposeFieldMethod .addStatement( "$T.e($L)", FieldsExposer.class, String.join( ",", fieldsWithNameExposed.stream() .map(ExposedField::getName) .collect(Collectors.toList()) ) ); componentExposedTypeBuilder.addMethod(exposeFieldMethod.build()); }
java
private void processComputed() { getMethodsWithAnnotation(component, Computed.class).forEach(method -> { ComputedKind kind = ComputedKind.GETTER; if ("void".equals(method.getReturnType().toString())) { kind = ComputedKind.SETTER; } String exposedMethodName = exposeExistingJavaMethodToJs(method); String fieldName = computedPropertyNameToFieldName(getComputedPropertyName(method)); TypeMirror propertyType = getComputedPropertyTypeFromMethod(method); fieldsWithNameExposed.add(new ExposedField(fieldName, propertyType)); optionsBuilder.addStatement( "options.addJavaComputed(p.$L, $T.getFieldName(this, () -> this.$L = $L), $T.$L)", exposedMethodName, VueGWTTools.class, fieldName, getFieldMarkingValueForType(propertyType), ComputedKind.class, kind ); }); addFieldsForComputedMethod(component, new HashSet<>()); }
java
private void addFieldsForComputedMethod(TypeElement component, Set<String> alreadyDone) { getMethodsWithAnnotation(component, Computed.class).forEach(method -> { String propertyName = computedPropertyNameToFieldName(getComputedPropertyName(method)); if (alreadyDone.contains(propertyName)) { return; } TypeMirror propertyType = getComputedPropertyTypeFromMethod(method); componentExposedTypeBuilder .addField(FieldSpec .builder(TypeName.get(propertyType), propertyName, Modifier.PROTECTED) .addAnnotation(JsProperty.class) .build()); alreadyDone.add(propertyName); }); getSuperComponentType(component) .ifPresent(superComponent -> addFieldsForComputedMethod(superComponent, alreadyDone)); }
java
private void processWatchers(MethodSpec.Builder createdMethodBuilder) { createdMethodBuilder.addStatement("Proto p = __proto__"); getMethodsWithAnnotation(component, Watch.class) .forEach(method -> processWatcher(createdMethodBuilder, method)); }
java
private void processWatcher(MethodSpec.Builder createdMethodBuilder, ExecutableElement method) { Watch watch = method.getAnnotation(Watch.class); String exposedMethodName = exposeExistingJavaMethodToJs(method); String watcherTriggerMethodName = addNewMethodToProto(); MethodSpec.Builder watcherMethodBuilder = MethodSpec .methodBuilder(watcherTriggerMethodName) .addModifiers(Modifier.PUBLIC) .addAnnotation(JsMethod.class) .returns(Object.class); String[] valueSplit = watch.value().split("\\."); String currentExpression = ""; for (int i = 0; i < valueSplit.length - 1; i++) { currentExpression += valueSplit[i]; watcherMethodBuilder.addStatement("if ($L == null) return null", currentExpression); currentExpression += "."; } watcherMethodBuilder.addStatement("return $L", watch.value()); componentExposedTypeBuilder.addMethod(watcherMethodBuilder.build()); createdMethodBuilder .addStatement("vue().$L(p.$L, p.$L, $T.of($L, $L))", "$watch", watcherTriggerMethodName, exposedMethodName, WatchOptions.class, watch.isDeep(), watch.isImmediate()); }
java
private void processPropValidators() { getMethodsWithAnnotation(component, PropValidator.class).forEach(method -> { PropValidator propValidator = method.getAnnotation(PropValidator.class); if (!TypeName.get(method.getReturnType()).equals(TypeName.BOOLEAN)) { printError("Method " + method.getSimpleName() + " annotated with PropValidator must return a boolean."); } String exposedMethodName = exposeExistingJavaMethodToJs(method); String propertyName = propValidator.value(); optionsBuilder.addStatement("options.addJavaPropValidator(p.$L, $S)", exposedMethodName, propertyName); }); }
java
private void processPropDefaultValues() { getMethodsWithAnnotation(component, PropDefault.class).forEach(method -> { PropDefault propValidator = method.getAnnotation(PropDefault.class); String exposedMethodName = exposeExistingJavaMethodToJs(method); String propertyName = propValidator.value(); optionsBuilder.addStatement("options.addJavaPropDefaultValue(p.$L, $S)", exposedMethodName, propertyName); }); }
java
private void processHooks(Set<ExecutableElement> hookMethodsFromInterfaces) { ElementFilter .methodsIn(component.getEnclosedElements()) .stream() .filter(method -> isHookMethod(component, method, hookMethodsFromInterfaces)) // Created hook is already added by createCreatedHook .filter(method -> !"created".equals(method.getSimpleName().toString())) .forEach(method -> { String exposedMethodName = exposeExistingJavaMethodToJs(method); String methodName = method.getSimpleName().toString(); optionsBuilder .addStatement("options.addHookMethod($S, p.$L)", methodName, exposedMethodName); }); }
java
private Set<ExecutableElement> getHookMethodsFromInterfaces() { return component .getInterfaces() .stream() .map(DeclaredType.class::cast) .map(DeclaredType::asElement) .map(TypeElement.class::cast) .flatMap(typeElement -> ElementFilter .methodsIn(typeElement.getEnclosedElements()) .stream()) .filter(method -> hasAnnotation(method, HookMethod.class)) .peek(this::validateHookMethod) .collect(Collectors.toSet()); }
java
private void processRenderFunction() { if (!hasInterface(processingEnv, component.asType(), HasRender.class)) { return; } componentExposedTypeBuilder.addMethod(MethodSpec .methodBuilder("vg$render") .addModifiers(Modifier.PUBLIC) .addAnnotation(JsMethod.class) .returns(VNode.class) .addParameter(CreateElementFunction.class, "createElementFunction") .addStatement("return super.render(new $T(createElementFunction))", VNodeBuilder.class) .build()); addMethodToProto("vg$render"); // Register the render method optionsBuilder.addStatement("options.addHookMethod($S, p.$L)", "render", "vg$render"); }
java
private void createCreatedHook(ComponentInjectedDependenciesBuilder dependenciesBuilder) { String hasRunCreatedFlagName = "vg$hrc_" + getSuperComponentCount(component); componentExposedTypeBuilder .addField( FieldSpec.builder(boolean.class, hasRunCreatedFlagName, Modifier.PUBLIC) .addAnnotation(JsProperty.class) .build() ); MethodSpec.Builder createdMethodBuilder = MethodSpec.methodBuilder("vg$created") .addModifiers(Modifier.PUBLIC) .addAnnotation(JsMethod.class); // Avoid infinite recursion in case calling the Java constructor calls Vue.js constructor // This can happen when extending an existing JS component createdMethodBuilder .addStatement("if ($L) return", hasRunCreatedFlagName) .addStatement("$L = true", hasRunCreatedFlagName); createdMethodBuilder .addStatement("vue().$L().proxyFields(this)", "$options"); injectDependencies(component, dependenciesBuilder, createdMethodBuilder); initFieldsValues(component, createdMethodBuilder); processWatchers(createdMethodBuilder); if (hasInterface(processingEnv, component.asType(), HasCreated.class)) { createdMethodBuilder.addStatement("super.created()"); } componentExposedTypeBuilder.addMethod(createdMethodBuilder.build()); // Register the hook addMethodToProto("vg$created"); optionsBuilder.addStatement("options.addHookMethod($S, p.$L)", "created", "vg$created"); }
java
private void initFieldsValues(TypeElement component, MethodSpec.Builder createdMethodBuilder) { // Do not init instance fields for abstract components if (component.getModifiers().contains(Modifier.ABSTRACT)) { return; } createdMethodBuilder.addStatement( "$T.initComponentInstanceFields(this, new $T())", VueGWTTools.class, component); }
java