/*
(non-Javadoc)

@see org.restcomm.protocols.ss7.map.api.service.supplementary. MAPServiceSupplementaryListener
#onUnstructuredSSResponseIndication(org.mobicents .protocols.ss7.map.api.service
.supplementary.UnstructuredSSResponseIndication)
421210
@Override
    public void onUnstructuredSSResponse(UnstructuredSSResponse unstrResInd) {
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("onUnstructuredSSResponseIndication for DialogId=%d", unstrResInd.getMAPDialog()
                    .getLocalDialogId()));
        }
        try {
            USSDString ussdStrObj = this.mapProvider.getMAPParameterFactory().createUSSDString("Your balance is 500");
            CBSDataCodingScheme ussdDataCodingScheme = new CBSDataCodingSchemeImpl(0x0F);
            MAPDialogSupplementary dialog = unstrResInd.getMAPDialog();

            AddressString msisdn = this.mapProvider.getMAPParameterFactory().createAddressString(
                    AddressNature.international_number, NumberingPlan.ISDN, "31628838002");

            dialog.addProcessUnstructuredSSResponse(((Long) dialog.getUserObject()).longValue(), ussdDataCodingScheme,
                    ussdStrObj);
            dialog.close(false);
        } catch (MAPException e) {
            logger.error("Error while sending UnstructuredSSRequest ", e);
        }
    }
94574
static void populateResponse(final ModelNode response, final ServiceController<?> serviceController) {
        response.set(serviceController.getState().toString());
    }
385681
@Override
    public void onUnstructuredSSRequest(UnstructuredSSRequest unstrReqInd) {
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Rx UnstructuredSSRequestIndication. USSD String=%s ", unstrReqInd.getUSSDString()));
        }
        MAPDialogSupplementary mapDialog = unstrReqInd.getMAPDialog();

        try {
            CBSDataCodingScheme ussdDataCodingScheme = new CBSDataCodingSchemeImpl(0x0f);

            USSDString ussdString = this.mapProvider.getMAPParameterFactory().createUSSDString("1", null, null);

            AddressString msisdn = this.mapProvider.getMAPParameterFactory()
                    .createAddressString(AddressNature.international_number, NumberingPlan.ISDN, "31628838002");

            mapDialog.addUnstructuredSSResponse(unstrReqInd.getInvokeId(), ussdDataCodingScheme, ussdString);
            mapDialog.send();

        } catch (MAPException e) {
            logger.error(
                    String.format("Error while sending UnstructuredSSResponse for Dialog=%d", mapDialog.getLocalDialogId()));
        }
    }
1194964
private HttpResponse executeUnparsed(boolean usingHead) throws IOException {
    HttpResponse response;
    if (uploader == null) {
      // normal request (not upload)
      response = buildHttpRequest(usingHead).execute();
    } else {
      // upload request
      GenericUrl httpRequestUrl = buildHttpRequestUrl();
      HttpRequest httpRequest = getAbstractGoogleClient()
          .getRequestFactory().buildRequest(requestMethod, httpRequestUrl, httpContent);
      boolean throwExceptionOnExecuteError = httpRequest.getThrowExceptionOnExecuteError();

      response = uploader.setInitiationHeaders(requestHeaders)
          .setDisableGZipContent(disableGZipContent).upload(httpRequestUrl);
      response.getRequest().setParser(getAbstractGoogleClient().getObjectParser());
      // process any error
      if (throwExceptionOnExecuteError && !response.isSuccessStatusCode()) {
        throw newExceptionOnError(response);
      }
    }
    // process response
    lastResponseHeaders = response.getHeaders();
    lastStatusCode = response.getStatusCode();
    lastStatusMessage = response.getStatusMessage();
    return response;
  }
586339
@Override
    public void addResponseHeader(String key, String value) {
        this.response.addResponseHeader(key, value);
    }
347856
@Override
    public void onUnstructuredSSNotifyRequest(UnstructuredSSNotifyRequest unstrNotifyInd) {
        // This error condition. Client should never receive the
        // UnstructuredSSNotifyRequestIndication
        logger.error(String.format("onUnstructuredSSNotifyRequestIndication for Dialog=%d and invokeId=%d",
                unstrNotifyInd.getMAPDialog().getLocalDialogId(), unstrNotifyInd.getInvokeId()));
    }
17752
protected void addNestedFormatter(String elementName, CmsXmlContentDefinition contentDefinition)
    throws CmsXmlException {

        if (contentDefinition.getSchemaType(elementName) == null) {
            throw new CmsXmlException(
                Messages.get().container(Messages.ERR_XMLCONTENT_INVALID_ELEM_MAPPING_1, elementName));
        }
        m_nestedFormatterElements.add(elementName);
    }
288688
public void addResponseHeaders(final HttpServletResponse servletResponse) {

        final String receivedParam = ofNullable(params.get("received")).orElse("");
        final List<String> includes = asList(ofNullable(params.get("include")).orElse(" ").split(" "));
        final List<String> omits = asList(ofNullable(params.get("omit")).orElse(" ").split(" "));

        final StringBuilder includeBuilder = new StringBuilder();
        final StringBuilder omitBuilder = new StringBuilder();

        if (!(value.equals("minimal") || receivedParam.equals("minimal"))) {
            final List<String> appliedPrefs = asList(PREFER_SERVER_MANAGED.toString(),
                    LDP_NAMESPACE + "PreferMinimalContainer",
                    LDP_NAMESPACE + "PreferMembership",
                    LDP_NAMESPACE + "PreferContainment");
            final List<String> includePrefs = asList(EMBED_CONTAINED.toString(),
                    INBOUND_REFERENCES.toString());
            includes.forEach(param -> includeBuilder.append(
                    (appliedPrefs.contains(param) || includePrefs.contains(param)) ? param + " " : ""));

            // Note: include params prioritized over omits during implementation
            omits.forEach(param -> omitBuilder.append(
                    (appliedPrefs.contains(param) && !includes.contains(param)) ? param + " " : ""));
        }

        // build the header for Preference Applied
        final String appliedReturn = value.equals("minimal") ? "return=minimal" : "return=representation";
        final String appliedReceived = receivedParam.equals("minimal") ? "received=minimal" : "";

        final StringBuilder preferenceAppliedBuilder = new StringBuilder(appliedReturn);
        preferenceAppliedBuilder.append(appliedReceived.length() > 0 ? "; " + appliedReceived : "");
        appendHeaderParam(preferenceAppliedBuilder, "include", includeBuilder.toString().trim());
        appendHeaderParam(preferenceAppliedBuilder, "omit", omitBuilder.toString().trim());

        servletResponse.addHeader("Preference-Applied", preferenceAppliedBuilder.toString().trim());

        servletResponse.addHeader("Vary", "Prefer");
    }
1008666
private AttachableResponse getAttachableResponse(JsonNode jsonNode) throws IOException {
		ObjectMapper mapper = new ObjectMapper();

		SimpleModule simpleModule = new SimpleModule("AttachableResponseDeserializer", new Version(1, 0, 0, null));
		simpleModule.addDeserializer(AttachableResponse.class, new AttachableResponseDeserializer());

		mapper.registerModule(simpleModule);
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

		return mapper.treeToValue(jsonNode, AttachableResponse.class);
	}
223623
public void addAnyTimeInterrogationResponse(long invokeId, SubscriberInfo subscriberInfo,
            MAPExtensionContainer extensionContainer) throws MAPException {
        doAddAnyTimeInterrogationResponse(false, invokeId, subscriberInfo, extensionContainer);
    }
503500
@Override
	protected RequestMapping parseRequestMapping(MethodDoc methodDoc) {
		ClassDoc controllerClass = methodDoc.containingClass();
		RequestMapping baseMapping = null;
		boolean controllerCustomizedMapping = false;
		boolean actionCustomizedMapping = false;
		Tag[] tags = controllerClass.tags(WRAPITaglet.NAME);
		if (tags.length > 0) {
			baseMapping = this.parseRequestMapping(tags[0]);
		}

		if (baseMapping == null) {
			AnnotationDesc[] baseAnnotations = controllerClass.annotations();
			baseMapping = this.parseRequestMapping(baseAnnotations);
			controllerCustomizedMapping = false;
		} else {
			controllerCustomizedMapping = true;
		}

		RequestMapping mapping = null;
		Tag[] methodTags = methodDoc.tags(WRAPITaglet.NAME);
		if (methodTags.length > 0) {
			mapping = this.parseRequestMapping(methodTags[0]);
		}
		if (mapping == null) {
			AnnotationDesc[] annotations = methodDoc.annotations();
			mapping = this.parseRequestMapping(annotations);
			actionCustomizedMapping = false;
		} else {
			actionCustomizedMapping = true;
		}
		RequestMapping result;
		if (baseMapping == null) {
			result = mapping;
		} else if (mapping == null) {
			result = baseMapping;
		} else {
			if(!actionCustomizedMapping || controllerCustomizedMapping) {
				mapping.setUrl(net.winroad.wrdoclet.utils.Util.urlConcat(
						baseMapping.getUrl(), mapping.getUrl()));
			}
			if (baseMapping.getMethodType() != null) {
				if (mapping.getMethodType() != null) {
					mapping.setMethodType(baseMapping.getMethodType() + ","
							+ mapping.getMethodType());
				} else {
					mapping.setMethodType(baseMapping.getMethodType());
				}
			}
			result = mapping;
		}
		if (result != null) {
			result.setTooltip(methodDoc.containingClass().simpleTypeName());
			result.setContainerName(methodDoc.containingClass()
					.simpleTypeName());
		}
		return result;
	}
802215
@Override
  protected TermsByQueryResponse newResponse(TermsByQueryRequest request, AtomicReferenceArray shardsResponses, ClusterState clusterState) {
    int successfulShards = 0;
    int failedShards = 0;
    int numTerms = 0;
    TermsSet[] termsSets = new TermsSet[shardsResponses.length()];
    List<ShardOperationFailedException> shardFailures = null;

    // we check each shard response
    for (int i = 0; i < shardsResponses.length(); i++) {
      Object shardResponse = shardsResponses.get(i);
      if (shardResponse == null) {
        // simply ignore non active shards
      } else if (shardResponse instanceof BroadcastShardOperationFailedException) {
        failedShards++;
        if (shardFailures == null) {
          shardFailures = new ArrayList<>();
        }
        logger.error("Shard operation failed", (BroadcastShardOperationFailedException) shardResponse);
        shardFailures.add(new DefaultShardOperationFailedException((BroadcastShardOperationFailedException) shardResponse));
      } else {
        // on successful shard response, just add to the array or responses so we can process them below
        // we calculate the total number of terms gathered across each shard so we can use it during
        // initialization of the final TermsResponse below (to avoid rehashing during merging)
        TermsByQueryShardResponse shardResp = ((TermsByQueryShardResponse) shardResponse);
        TermsSet terms = shardResp.getTerms();
        termsSets[i] = terms;
        numTerms += terms.size();
        successfulShards++;
      }
    }

    // Merge the responses

    try {
      // NumericTermsSet is responsible for the merge, set size to avoid rehashing on certain implementations.
      long expectedElements = request.expectedTerms() != null ? request.expectedTerms() : numTerms;
      TermsSet termsSet = TermsSet.newTermsSet(expectedElements, request.termsEncoding(), breakerService.getBreaker(CircuitBreaker.REQUEST));

      TermsByQueryResponse rsp;
      try {
        for (int i = 0; i < termsSets.length; i++) {
          TermsSet terms = termsSets[i];
          if (terms != null) {
            termsSet.merge(terms);
            terms.release(); // release the shard terms set and adjust the circuit breaker
            termsSets[i] = null;
          }
        }

        long tookInMillis = System.currentTimeMillis() - request.nowInMillis();

        rsp = new TermsByQueryResponse(termsSet, tookInMillis, shardsResponses.length(), successfulShards, failedShards, shardFailures);
      }
      finally {
        // we can now release the terms set and adjust the circuit breaker, since the TermsByQueryResponse holds an
        // encoded version of the terms set
        termsSet.release();
      }

      return rsp;
    }
    finally { // If something happens, release the terms sets and adjust the circuit breaker
      for (int i = 0; i < termsSets.length; i++) {
        TermsSet terms = termsSets[i];
        if (terms != null) {
          terms.release();
        }
      }
    }
  }
1127159
@Override
	public void renderHead(IHeaderResponse response) {
		super.renderHead(response);
		
		List<FeedbackMessage> msgs = model.getObject();
		if(msgs.size()>0){
			for(Component component: messages.keySet()){
				StringBuffer sb = new StringBuffer();
				for(FeedbackMessage msg : messages.get(component)){
					sb.append(msg.getMessage()+"\n");
					msg.markRendered();
				}
				
				String script = "$(\"#"+component.getMarkupId()+"\")"
						+ ".popover({ 'trigger': 'focus', "
								   + "'placement': 'top', "
								   + "'content': \""+StringEscapeUtils.escapeEcmaScript(sb.toString())+"\", "
								   + "'template': '<div class=\"popover feedback-popover\"><div class=\"arrow\"></div><div class=\"popover-inner\"><h3 class=\"popover-title\"></h3><div class=\"popover-content\"><p></p></div></div></div>'"
						+ "});";
				script += "$(\"#"+component.getMarkupId()+"\").keypress(function(){ $(\"#"+this.getMarkupId()+"\").removeClass('has-error'); $(this).popover('destroy'); });";
				response.render(OnDomReadyHeaderItem.forScript(script));
			}
		}
		
	}
641872
public void onSuccess (final WriteResponse response) {
    for (final Thunk thunk: this.thunks) {
      thunk.callback.onSuccess(new WriteResponse() {
        @Override
        public Object getRawResponse() {
          return response.getRawResponse();
        }

        @Override
        public String getStringResponse() {
          return response.getStringResponse();
        }

        @Override
        public long bytesWritten() {
          return thunk.sizeInBytes;
        }
      });
    }
  }
130063
protected I_CmsFormatterBean readFormatter(CmsUUID structureId) {

        I_CmsFormatterBean formatterBean = null;
        CmsResource formatterRes = null;
        try {
            formatterRes = m_cms.readResource(structureId);
            CmsFile formatterFile = m_cms.readFile(formatterRes);
            CmsFormatterBeanParser parser = new CmsFormatterBeanParser(m_cms, m_settingConfigs);
            CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, formatterFile);
            formatterBean = parser.parse(content, formatterRes.getRootPath(), "" + formatterRes.getStructureId());
        } catch (Exception e) {

            if (formatterRes == null) {
                // normal case if resources get deleted, should not be written to the error channel
                LOG.info("Could not read formatter with id " + structureId);
            } else {
                LOG.error(
                    "Error while trying to read formatter configuration "
                        + formatterRes.getRootPath()
                        + ":    "
                        + e.getLocalizedMessage(),
                    e);
            }
        }
        return formatterBean;
    }
87207
@Deprecated
    @JsonProperty("messaging_service_sid")
    public void setMessagingServiceSID(String messagingServiceSID) throws IllegalArgumentException {
        if (from != null) {
            throw new IllegalArgumentException("You must specify either `from` or `messagingServiceSID`, but not both");
        }
        this.messagingServiceSID = messagingServiceSID;
    }
2690
private void processBatchRequestResponse(CloseableHttpResponse response) throws IOException,
      UnexpectedResponseException {
    String entityStr = EntityUtils.toString(response.getEntity());
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode >= 400) {
      throw new RuntimeException("Failed due to " + entityStr + " (Detail: "
          + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE) + " )");
    }

    JsonObject jsonBody = new JsonParser().parse(entityStr).getAsJsonObject();
    if (!jsonBody.get("hasErrors").getAsBoolean()) {
      return;
    }

    JsonArray results = jsonBody.get("results").getAsJsonArray();
    for (JsonElement jsonElem : results) {
      JsonObject json = jsonElem.getAsJsonObject();
      int subStatusCode = json.get("statusCode").getAsInt();
      if (subStatusCode < 400) {
        continue;
      } else if (subStatusCode == 400
                 && Operation.INSERT_ONLY_NOT_EXIST.equals(operation)) {
        JsonElement resultJsonElem = json.get("result");
        Preconditions.checkNotNull(resultJsonElem, "Error response should contain result property");
        JsonObject resultJsonObject = resultJsonElem.getAsJsonArray().get(0).getAsJsonObject();
        if (isDuplicate(resultJsonObject, subStatusCode)) {
          continue;
        }
      }
      throw new RuntimeException("Failed due to " + jsonBody + " (Detail: "
          + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE) + " )");
    }
  }