Java Code Examples for javax.ws.rs.core.HttpHeaders#getHeaderString()

The following examples show how to use javax.ws.rs.core.HttpHeaders#getHeaderString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ResteasyBizHandler.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
/**
 * 获取远端地址
 *
 * @param headers
 * @param channel
 * @return
 */
protected InetSocketAddress getRemoteAddress(final HttpHeaders headers, final Channel channel) {
    String remoteIp = headers.getHeaderString("X-Forwarded-For");
    if (remoteIp == null) {
        remoteIp = headers.getHeaderString("X-Real-IP");
    }
    if (remoteIp != null) {
        // 可能是vip nginx等转发后的ip,多次转发用逗号分隔
        int pos = remoteIp.indexOf(',');
        remoteIp = pos > 0 ? remoteIp.substring(0, pos).trim() : remoteIp.trim();
    }
    InetSocketAddress remote = (InetSocketAddress) channel.remoteAddress();
    if (remoteIp != null && !remoteIp.isEmpty()) {
        return InetSocketAddress.createUnresolved(remoteIp, remote.getPort());
    } else { // request取不到就从channel里取
        return remote;
    }
}
 
Example 2
Source File: GremlinAPI.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@POST
@Timed
@Compress
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON_WITH_CHARSET)
public Response post(@Context HugeConfig conf,
                     @Context HttpHeaders headers,
                     String request) {
    /* The following code is reserved for forwarding request */
    // context.getRequestDispatcher(location).forward(request, response);
    // return Response.seeOther(UriBuilder.fromUri(location).build())
    // .build();
    // Response.temporaryRedirect(UriBuilder.fromUri(location).build())
    // .build();
    String auth = headers.getHeaderString(HttpHeaders.AUTHORIZATION);
    Response response = this.client().doPostRequest(auth, request);
    gremlinInputHistogram.update(request.length());
    gremlinOutputHistogram.update(response.getLength());
    return transformResponseIfNeeded(response);
}
 
Example 3
Source File: ZKOperator.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
public void completeSegmentOperations(String rawTableName, SegmentMetadata segmentMetadata,
    URI finalSegmentLocationURI, File currentSegmentLocation, boolean enableParallelPushProtection,
    HttpHeaders headers, String zkDownloadURI, boolean moveSegmentToFinalLocation)
    throws Exception {
  String offlineTableName = TableNameBuilder.OFFLINE.tableNameWithType(rawTableName);
  String segmentName = segmentMetadata.getName();

  // Brand new segment, not refresh, directly add the segment
  ZNRecord segmentMetadataZnRecord =
      _pinotHelixResourceManager.getSegmentMetadataZnRecord(offlineTableName, segmentName);
  if (segmentMetadataZnRecord == null) {
    LOGGER.info("Adding new segment {} from table {}", segmentName, rawTableName);
    String crypter = headers.getHeaderString(FileUploadDownloadClient.CustomHeaders.CRYPTER);
    processNewSegment(segmentMetadata, finalSegmentLocationURI, currentSegmentLocation, zkDownloadURI, crypter,
        rawTableName, segmentName, moveSegmentToFinalLocation);
    return;
  }

  LOGGER.info("Segment {} from table {} already exists, refreshing if necessary", segmentName, rawTableName);

  processExistingSegment(segmentMetadata, finalSegmentLocationURI, currentSegmentLocation,
      enableParallelPushProtection, headers, zkDownloadURI, offlineTableName, segmentName, segmentMetadataZnRecord,
      moveSegmentToFinalLocation);
}
 
Example 4
Source File: ZKOperator.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private void checkCRC(HttpHeaders headers, String offlineTableName, String segmentName, long existingCrc) {
  String expectedCrcStr = headers.getHeaderString(HttpHeaders.IF_MATCH);
  if (expectedCrcStr != null) {
    long expectedCrc;
    try {
      expectedCrc = Long.parseLong(expectedCrcStr);
    } catch (NumberFormatException e) {
      throw new ControllerApplicationException(LOGGER,
          "Caught exception for segment: " + segmentName + " of table: " + offlineTableName
              + " while parsing IF-MATCH CRC: \"" + expectedCrcStr + "\"", Response.Status.PRECONDITION_FAILED);
    }
    if (expectedCrc != existingCrc) {
      throw new ControllerApplicationException(LOGGER,
          "For segment: " + segmentName + " of table: " + offlineTableName + ", expected CRC: " + expectedCrc
              + " does not match existing CRC: " + existingCrc, Response.Status.PRECONDITION_FAILED);
    }
  }
}
 
Example 5
Source File: ApiUmaProtectionService.java    From oxTrust with MIT License 6 votes vote down vote up
@Override
public Response processAuthorization(HttpHeaders headers, ResourceInfo resourceInfo) {
	Response authorizationResponse = null;
	String authorization = headers.getHeaderString("Authorization");
	log.info("==== API Service call intercepted ====");
	log.info("Authorization header {} found", StringUtils.isEmpty(authorization) ? "not" : "");
	try {
		if (appConfiguration.isOxTrustApiTestMode()) {
			log.info("API Test Mode is ACTIVE");
			authorizationResponse = processTestModeAuthorization(authorization);
		} else if (isEnabled()) {
			log.info("API is protected by UMA");
			authorizationResponse = processUmaAuthorization(authorization, resourceInfo);
		} else {
			log.info(
					"Please activate UMA or test mode to protect your API endpoints. Read the Gluu API docs to learn more");
			authorizationResponse = getErrorResponse(Response.Status.UNAUTHORIZED, "API not protected");
		}
	} catch (Exception e) {
		log.error(e.getMessage(), e);
		authorizationResponse = getErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage());
	}
	return authorizationResponse;
}
 
Example 6
Source File: OAuth2SecurityInterceptor.java    From msf4j with Apache License 2.0 6 votes vote down vote up
@Override
public boolean interceptRequest(Request request, Response response) throws Exception {
    SecurityErrorCode errorCode;

    try {
        HttpHeaders headers = request.getHeaders();
        String authHeader = headers.getHeaderString(AUTHORIZATION_HTTP_HEADER);
        if (authHeader != null && !authHeader.isEmpty()) {
            return validateToken(authHeader);
        } else {
            throw new MSF4JSecurityException(SecurityErrorCode.AUTHENTICATION_FAILURE,
                    "Missing Authorization header is the request.`");
        }
    } catch (MSF4JSecurityException e) {
        errorCode = e.getErrorCode();
        log.error(e.getMessage() + " Requested Path: " + request.getUri());
    }

    handleSecurityError(errorCode, response);
    return false;
}
 
Example 7
Source File: CustomJWTClaimsInterceptor.java    From msf4j with Apache License 2.0 6 votes vote down vote up
@Override
public boolean interceptRequest(Request request, Response response) throws Exception {
    HttpHeaders headers = request.getHeaders();
    if (headers != null) {
        String jwtHeader = headers.getHeaderString(JWT_HEADER);
        if (jwtHeader != null) {
            SignedJWT signedJWT = SignedJWT.parse(jwtHeader);
            ReadOnlyJWTClaimsSet readOnlyJWTClaimsSet = signedJWT.getJWTClaimsSet();
            if (readOnlyJWTClaimsSet != null) {
                // Do something with claims
                return true;
            }
        }
    }
    response.setHeader(javax.ws.rs.core.HttpHeaders.WWW_AUTHENTICATE, AUTH_TYPE_JWT);
    response.setStatus(javax.ws.rs.core.Response.Status.UNAUTHORIZED.getStatusCode());
    return false;
}
 
Example 8
Source File: ServerOutInterceptor.java    From peer-os with Apache License 2.0 5 votes vote down vote up
/**
 * Intercepts a message. interceptor chain will take care of this.
 */
@Override
public void handleMessage( final Message message )
{
    try
    {
        if ( InterceptorState.SERVER_OUT.isActive( message ) )
        {
            //obtain client request
            HttpServletRequest req = ( HttpServletRequest ) message.getExchange().getInMessage()
                                                                   .get( AbstractHTTPDestination.HTTP_REQUEST );

            if ( req.getLocalPort() == Common.DEFAULT_PUBLIC_SECURE_PORT )
            {
                HttpHeaders headers = new HttpHeadersImpl( message.getExchange().getInMessage() );
                String subutaiHeader = headers.getHeaderString( Common.SUBUTAI_HTTP_HEADER );
                String path = req.getRequestURI();

                if ( path.startsWith( "/rest/v1/peer" ) )
                {
                    handlePeerMessage( subutaiHeader, message );
                }
                else
                {
                    final String prefix = "/rest/v1/env";
                    if ( path.startsWith( prefix ) )
                    {
                        String s = path.substring( prefix.length() + 1 );
                        String environmentId = s.substring( 0, s.indexOf( "/" ) );
                        handleEnvironmentMessage( subutaiHeader, environmentId, message );
                    }
                }
            }
        }
    }
    catch ( Exception e )
    {
        throw new Fault( e );
    }
}
 
Example 9
Source File: HttpHeadersImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetHeaderString() throws Exception {

    Message m = createMessage(createHeaders());
    HttpHeaders h = new HttpHeadersImpl(m);

    String date = h.getHeaderString("Date");
    assertEquals("Tue, 21 Oct 2008 17:00:00 GMT", date);
}
 
Example 10
Source File: ScimUmaProtectionService.java    From oxTrust with MIT License 5 votes vote down vote up
/**
    * This method checks whether the authorization header is present and valid before scim service methods can be actually
    * called.
    * @param headers An object holding HTTP headers
    * @param uriInfo An object that allows access to request URI information
    * @return A null value if the authorization was successful, otherwise a Response object is returned signaling an
    * authorization error
    */
public Response processAuthorization(HttpHeaders headers, ResourceInfo resourceInfo){

       //Comment this method body if you want to skip the authorization check and proceed straight to use your SCIM service.
       //This is useful under certain circumstances while doing development
       //log.warn("Bypassing protection TEMPORARILY");

       Response authorizationResponse = null;
       String authorization = headers.getHeaderString("Authorization");
       log.info("==== SCIM Service call intercepted ====");
       log.info("Authorization header {} found", StringUtils.isEmpty(authorization) ? "not" : "");

       try {
           //Test mode may be removed in upcoming versions of Gluu Server...
           if (jsonConfigurationService.getOxTrustappConfiguration().isScimTestMode()) {
               log.info("SCIM Test Mode is ACTIVE");
               authorizationResponse = processTestModeAuthorization(authorization);
           }
           else
           if (isEnabled()){
               log.info("SCIM is protected by UMA");
               authorizationResponse = processUmaAuthorization(authorization, resourceInfo);
           }
           else{
               log.info("Please activate UMA or test mode to protect your SCIM endpoints. Read the Gluu SCIM docs to learn more");
               authorizationResponse= getErrorResponse(Response.Status.UNAUTHORIZED, "SCIM API not protected");
           }
       }
       catch (Exception e){
           log.error(e.getMessage(), e);
           authorizationResponse=getErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage());
       }
       return authorizationResponse;

   }
 
Example 11
Source File: PinotSegmentUploadDownloadRestletResource.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@Nullable
private String extractHttpHeader(HttpHeaders headers, String name) {
  String value = headers.getHeaderString(name);
  if (value != null) {
    LOGGER.info("HTTP Header: {} is: {}", name, value);
  }
  return value;
}
 
Example 12
Source File: TrellisWebDAV.java    From trellis with Apache License 2.0 5 votes vote down vote up
private IRI getDestination(final HttpHeaders headers, final String baseUrl) {
    final String destination = headers.getHeaderString("Destination");
    if (destination == null) {
        throw new BadRequestException("Missing Destination header");
    } else if (!destination.startsWith(baseUrl)) {
        throw new BadRequestException("Out-of-domain Destination!");
    }
    return services.getResourceService().toInternal(rdf.createIRI(destination), baseUrl);
}
 
Example 13
Source File: RestTracerAdapter.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 适配服务端serverReceived
 */
public static void serverReceived(NettyHttpRequest request) {
    try {
        SofaRequest sofaRequest = new SofaRequest();

        HttpHeaders headers = request.getHttpHeaders();
        String rpcTraceContext = headers.getHeaderString(RemotingConstants.NEW_RPC_TRACE_NAME);
        if (StringUtils.isNotBlank(rpcTraceContext)) {
            // 新格式
            sofaRequest.addRequestProp(RemotingConstants.NEW_RPC_TRACE_NAME, rpcTraceContext);
        } else {
            String traceIdKey = headers.getHeaderString(RemotingConstants.HTTP_HEADER_TRACE_ID_KEY);
            String rpcIdKey = headers.getHeaderString(RemotingConstants.HTTP_HEADER_RPC_ID_KEY);
            if (StringUtils.isEmpty(rpcIdKey)) {
                rpcIdKey = request.getUri().getQueryParameters().getFirst(RemotingConstants.RPC_ID_KEY);
            }
            if (StringUtils.isEmpty(traceIdKey)) {
                traceIdKey = request.getUri().getQueryParameters().getFirst(RemotingConstants.TRACE_ID_KEY);
            }

            if (StringUtils.isNotEmpty(traceIdKey) && StringUtils.isNotEmpty(rpcIdKey)) {
                Map<String, String> map = new HashMap<String, String>();
                map.put(RemotingConstants.TRACE_ID_KEY, traceIdKey);
                map.put(RemotingConstants.RPC_ID_KEY, rpcIdKey);
                String penAttrs = headers.getHeaderString(RemotingConstants.PEN_ATTRS_KEY);
                map.put(RemotingConstants.PEN_ATTRS_KEY, penAttrs);
                sofaRequest.addRequestProp(RemotingConstants.RPC_TRACE_NAME, map);
            }
        }
        Tracers.serverReceived(sofaRequest);

        RestBaggageItemsHandler.decodeBaggageItemsFromRequest(request, sofaRequest);
    } catch (Throwable t) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn(LogCodes.getLog(LogCodes.ERROR_TRACER_UNKNOWN_EXP, "receive", "rest", "server"), t);
        }
    }
}
 
Example 14
Source File: MaxBodySizeResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@POST
@Produces("text/plain")
@Consumes("application/octet-stream")
public String post(byte[] body, @Context HttpHeaders headers) {
    return (headers.getHeaderString(HttpHeaders.CONTENT_LENGTH) == null ? "chunked" : "cl")
            + new String(body, StandardCharsets.UTF_8);
}
 
Example 15
Source File: GremlinAPI.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
@GET
@Timed
@Compress(buffer=(1024 * 40))
@Produces(APPLICATION_JSON_WITH_CHARSET)
public Response get(@Context HugeConfig conf,
                    @Context HttpHeaders headers,
                    @Context UriInfo uriInfo) {
    String auth = headers.getHeaderString(HttpHeaders.AUTHORIZATION);
    String query = uriInfo.getRequestUri().getRawQuery();
    MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
    Response response = this.client().doGetRequest(auth, params);
    gremlinInputHistogram.update(query.length());
    gremlinOutputHistogram.update(response.getLength());
    return transformResponseIfNeeded(response);
}
 
Example 16
Source File: RequestId.java    From soabase with Apache License 2.0 4 votes vote down vote up
public static String get(HttpHeaders headers)
{
    return headers.getHeaderString(REQUEST_ID_HEADER_NAME);
}
 
Example 17
Source File: ServerInInterceptor.java    From peer-os with Apache License 2.0 4 votes vote down vote up
/**
 * Intercepts a message. Interceptors should NOT invoke handleMessage or handleFault on the next interceptor - the
 * interceptor chain will take care of this.
 */
@Override
public void handleMessage( final Message message )
{
    try
    {
        if ( InterceptorState.SERVER_IN.isActive( message ) )
        {
            //obtain client request
            HttpServletRequest req = ( HttpServletRequest ) message.getExchange().getInMessage()
                                                                   .get( AbstractHTTPDestination.HTTP_REQUEST );

            if ( req.getLocalPort() == Common.DEFAULT_PUBLIC_SECURE_PORT )
            {
                HttpHeaders headers = new HttpHeadersImpl( message.getExchange().getInMessage() );
                String subutaiHeader = headers.getHeaderString( Common.SUBUTAI_HTTP_HEADER );

                String path = req.getRequestURI();

                if ( path.startsWith( "/rest/v1/peer" ) )
                {
                    handlePeerMessage( subutaiHeader, message );
                }
                else
                {
                    final String prefix = "/rest/v1/env";
                    if ( path.startsWith( prefix ) )
                    {
                        String s = path.substring( prefix.length() + 1 );
                        String environmentId = s.substring( 0, s.indexOf( "/" ) );
                        handleEnvironmentMessage( subutaiHeader, environmentId, message );
                    }
                }
            }
        }
    }
    catch ( Exception e )
    {
        throw new Fault( e );
    }
}
 
Example 18
Source File: AccessControlInterceptor.java    From peer-os with Apache License 2.0 4 votes vote down vote up
protected Session authenticateAccess( Message message, HttpServletRequest request )
{
    String sptoken;

    if ( message == null )
    {
        //***********internal auth ********* for registration , 8444 port and 8443 open REST endpoints
        return identityManager.loginSystemUser();
    }
    else
    {
        String bearerToken = getBearerToken( request );
        if ( bearerToken != null )
        {
            return identityManager.login( request, message );
        }
        else
        {
            sptoken = request.getParameter( "sptoken" );

            if ( StringUtils.isBlank( sptoken ) )
            {
                HttpHeaders headers = new HttpHeadersImpl( message.getExchange().getInMessage() );
                sptoken = headers.getHeaderString( "sptoken" );
            }

            //******************Get sptoken from cookies *****************

            if ( StringUtils.isBlank( sptoken ) )
            {
                Cookie[] cookies = request.getCookies();
                for ( final Cookie cookie : cookies )
                {
                    if ( "sptoken".equals( cookie.getName() ) )
                    {
                        sptoken = cookie.getValue();
                    }
                }
            }

            if ( StringUtils.isBlank( sptoken ) )
            {
                return null;
            }
            else
            {
                return identityManager.login( IdentityManager.TOKEN_ID, sptoken );
            }
        }
    }
}
 
Example 19
Source File: MaxBodySizeResource.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@POST
@Produces("text/plain")
@Consumes("text/plain")
public String post(String body, @Context HttpHeaders headers) {
    return (headers.getHeaderString(HttpHeaders.CONTENT_LENGTH) == null ? "chunked" : "cl") + body;
}
 
Example 20
Source File: ZKOperator.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
private void processExistingSegment(SegmentMetadata segmentMetadata, URI finalSegmentLocationURI,
    File currentSegmentLocation, boolean enableParallelPushProtection, HttpHeaders headers, String zkDownloadURI,
    String offlineTableName, String segmentName, ZNRecord znRecord, boolean moveSegmentToFinalLocation)
    throws Exception {

  OfflineSegmentZKMetadata existingSegmentZKMetadata = new OfflineSegmentZKMetadata(znRecord);
  long existingCrc = existingSegmentZKMetadata.getCrc();

  // Check if CRC match when IF-MATCH header is set
  checkCRC(headers, offlineTableName, segmentName, existingCrc);

  // Check segment upload start time when parallel push protection enabled
  if (enableParallelPushProtection) {
    // When segment upload start time is larger than 0, that means another upload is in progress
    long segmentUploadStartTime = existingSegmentZKMetadata.getSegmentUploadStartTime();
    if (segmentUploadStartTime > 0) {
      if (System.currentTimeMillis() - segmentUploadStartTime > _controllerConf.getSegmentUploadTimeoutInMillis()) {
        // Last segment upload does not finish properly, replace the segment
        LOGGER
            .error("Segment: {} of table: {} was not properly uploaded, replacing it", segmentName, offlineTableName);
        _controllerMetrics.addMeteredGlobalValue(ControllerMeter.NUMBER_SEGMENT_UPLOAD_TIMEOUT_EXCEEDED, 1L);
      } else {
        // Another segment upload is in progress
        throw new ControllerApplicationException(LOGGER,
            "Another segment upload is in progress for segment: " + segmentName + " of table: " + offlineTableName
                + ", retry later", Response.Status.CONFLICT);
      }
    }

    // Lock the segment by setting the upload start time in ZK
    existingSegmentZKMetadata.setSegmentUploadStartTime(System.currentTimeMillis());
    if (!_pinotHelixResourceManager
        .updateZkMetadata(offlineTableName, existingSegmentZKMetadata, znRecord.getVersion())) {
      throw new ControllerApplicationException(LOGGER,
          "Failed to lock the segment: " + segmentName + " of table: " + offlineTableName + ", retry later",
          Response.Status.CONFLICT);
    }
  }

  // Reset segment upload start time to unlock the segment later
  // NOTE: reset this value even if parallel push protection is not enabled so that segment can recover in case
  // previous segment upload did not finish properly and the parallel push protection is turned off
  existingSegmentZKMetadata.setSegmentUploadStartTime(-1);

  try {
    // Modify the custom map in segment ZK metadata
    String segmentZKMetadataCustomMapModifierStr =
        headers.getHeaderString(FileUploadDownloadClient.CustomHeaders.SEGMENT_ZK_METADATA_CUSTOM_MAP_MODIFIER);
    SegmentZKMetadataCustomMapModifier segmentZKMetadataCustomMapModifier;
    if (segmentZKMetadataCustomMapModifierStr != null) {
      segmentZKMetadataCustomMapModifier =
          new SegmentZKMetadataCustomMapModifier(segmentZKMetadataCustomMapModifierStr);
    } else {
      // By default, use REPLACE modify mode
      segmentZKMetadataCustomMapModifier =
          new SegmentZKMetadataCustomMapModifier(SegmentZKMetadataCustomMapModifier.ModifyMode.REPLACE, null);
    }
    existingSegmentZKMetadata
        .setCustomMap(segmentZKMetadataCustomMapModifier.modifyMap(existingSegmentZKMetadata.getCustomMap()));

    // Update ZK metadata and refresh the segment if necessary
    long newCrc = Long.valueOf(segmentMetadata.getCrc());
    if (newCrc == existingCrc) {
      LOGGER.info(
          "New segment crc '{}' is the same as existing segment crc for segment '{}'. Updating ZK metadata without refreshing the segment.",
          newCrc, segmentName);
      // NOTE: even though we don't need to refresh the segment, we should still update creation time and refresh time
      // (creation time is not included in the crc)
      existingSegmentZKMetadata.setCreationTime(segmentMetadata.getIndexCreationTime());
      existingSegmentZKMetadata.setRefreshTime(System.currentTimeMillis());
      if (!_pinotHelixResourceManager.updateZkMetadata(offlineTableName, existingSegmentZKMetadata)) {
        throw new RuntimeException(
            "Failed to update ZK metadata for segment: " + segmentName + " of table: " + offlineTableName);
      }
    } else {
      // New segment is different with the existing one, update ZK metadata and refresh the segment
      LOGGER.info(
          "New segment crc {} is different than the existing segment crc {}. Updating ZK metadata and refreshing segment {}",
          newCrc, existingCrc, segmentName);
      if (moveSegmentToFinalLocation) {
        moveSegmentToPermanentDirectory(currentSegmentLocation, finalSegmentLocationURI);
        LOGGER.info("Moved segment {} from temp location {} to {}", segmentName,
            currentSegmentLocation.getAbsolutePath(), finalSegmentLocationURI.getPath());
      } else {
        LOGGER.info("Skipping segment move, keeping segment {} from table {} at {}", segmentName, offlineTableName,
            zkDownloadURI);
      }

      String crypter = headers.getHeaderString(FileUploadDownloadClient.CustomHeaders.CRYPTER);
      _pinotHelixResourceManager
          .refreshSegment(offlineTableName, segmentMetadata, existingSegmentZKMetadata, zkDownloadURI, crypter);
    }
  } catch (Exception e) {
    if (!_pinotHelixResourceManager.updateZkMetadata(offlineTableName, existingSegmentZKMetadata)) {
      LOGGER.error("Failed to update ZK metadata for segment: {} of table: {}", segmentName, offlineTableName);
    }
    throw e;
  }
}